ofstream outputfile () в цикле while обычно делает пустой файл - PullRequest
0 голосов
/ 15 мая 2018

Я столкнулся с забавной проблемой с этим кодом, но мне интересно, почему это произошло:

#include <stdio.h>
#include <unistd.h>
#include <iostream>
#include <wiringPi.h>

#define BUTTON_PORT 25
#define FILE_PATH "/path/to/output.txt"


int main(void) {

    int buttonState = 0;
    int pastButtonState = 0;
    int buttonCounter = 0;

    if (wiringPiSetupGpio() == -1) return 1;
    pinMode(BUTTON_PORT, INPUT);

    while(buttonCounter < 100){

        if (buttonState == 1 && pastButtonState == 0) buttonCounter++;

        usleep(100);
        ofstream outputfile(FILE_PATH);
        outputfile << buttonCounter << endl;
        outputfile.flush();
        outputfile.close();

        pastButtonState = buttonState;

    }

Я ожидал, что output.txt покажет текущее число * из 1005 *, но файл всегда пуст, и 110 раз файл показывает # из buttonCounter.(с непрерывным exec less /path/to/output.txt)

Я знаю, что определенное повторение ofstream outputfile в while цикле не является хорошим решением, но я понятия не имею, почему output.txt обычно пуст.

Я мог бы подумать, что некрасиво использовать ofstream outputfile в цикле while, поскольку ofstream outputfile занимает некоторое время, поскольку это немного высокоуровневая функция.


При установке outputfile связанной функциив

if (buttonState == 1 && pastButtonState == 0) {...}

работает нормально.Есть идеи?

1 Ответ

0 голосов
/ 15 мая 2018

Я бы добавил проверку, чтобы убедиться, что файл был успешно открыт.Кроме того, результаты выполнения less для файла не являются надежным способом проверки содержимого файла во время работы программы.usleep(100) не дает вам достаточно времени, чтобы проверить содержимое файла до его повторного открытия.

Я предлагаю следующее изменение вашего кода.

while(buttonCounter < 100){

   if (buttonState == 1 && pastButtonState == 0) buttonCounter++;

   writeToFile(buttonCounter, FILE_PATH);
   showContentsOfFile(FILE_PATH);
   `
   pastButtonState = buttonState;
}

, где writeToFileэто:

void writeToFile(int buttonState, std::string const& file)
{
   std::ofstream outputfile(file);
   if ( outputfile )
   {
      outputfile << buttonCounter << std::endl;
   }
   else
   {
      std::cerr << "Unable to open " << file << " for writing to.\n";
   }
}

и showContentsOfFile это:

void showContentsOfFile(std::string const& file)
{
   std::ifstream inputfile(file);
   if ( outputfile )
   {
      int buttonCounter;
      if ( inputfile >> buttonCounter )
      {
         std::cout << "Button counter: " << buttonCounter << std::endl;
      }
      else
      {
         std::cerr << "Unable to read buttonCounter from file " << file << std::endl;
      }
   }
   else
   {
      std::cerr << "Unable to open " << file << " for reading from.\n";
   }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...