How do I display a message while something is being written to a file?

The task is as follows: there is a cyclic processing of character data, there are two open files - one for reading and the other for writing. Under a certain condition, you need to display a message to the user without interrupting the program. Here is the code where the output doesn't work:

freopen("output.txt", "w", stdout);

for (i = 0; i <= rest; i++) {
    cout << "-";        // пишем в файл
    if (ab >= 1)
        cout << "0" << cj;    // пишем в файл
    else
        printf("вариант ", i, " c ошибкой");    // пишем на экран (не работает)
    cout << "-";        // пишем в файл
}

fclose(stdout);

So it will probably be clearer.

Author: Nicolas Chabanovsky, 2011-09-10

5 answers

If the user is not expected to respond, then simply:

while(...) //
{
 if (условие)
 {
   cout<<сообщение;
 }
}

The program will not be interrupted, it will just work out if and the execution will go on.

If a response is expected from the user, then run in a separate thread:

while(...) // цикл обработки
{
  if (условие)
  {
    Запустить_поток(функция_печати_сообщения);
  }
}

void функция_печати_сообщения()
{
  cout<<информация для пользователя;
}

How to start a thread is a separate issue. Or using the OS API, or something cross-platform like boost.threads. Also note that if the print message function uses some shared data( shared data), then you need to block access to them for the duration of the function.

 5
Author: fogbit, 2011-09-10 09:19:14

To do this, write to the disk in another thread (thread) =) And use the main one to inform the user and receive his instructions.

 1
Author: Алексей Сонькин, 2011-09-10 09:18:46

First, as we wrote above, there is an error in calling the printf function. Secondly, even if you call the printf function correctly, you still won't see anything on the screen, because you yourself reassigned stdout (and printf uses it) to the file "output.txt"

 1
Author: Сирошка, 2011-09-19 07:05:12

It is much easier to enter another file variable ofstream fo("output.txt"[, ofstream:: out]); fo

 1
Author: DiaG, 2011-12-20 21:38:03

Incorrect syntax of the printf command. You should write like this: printf("вариант %d c ошибкой", i); UPD: either I didn't understand something, or something else, but cout outputs to the screen. To output to a file, I use fprintf.

 0
Author: 3JIoi_Hy6, 2011-09-14 18:14:59