LINUX.ORG.RU

[C++] Работа с fsream, чтение и запись.

 


0

0

Есть такой код, он должен дописать в конец файла строку, вывести весь файл, и под конец дописать еще одну строку в файл.

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int
main(int argc, char *argv[])
{
  fstream file;
  string str;

  file.open("file", fstream::in | fstream::out);

  if (!file.is_open())
    file.open("file", fstream::in | fstream::out | fstream::trunc);

  if (file.is_open())
    {
      file.seekp(0, ios::end);
      file << "hello\n";
   
      file.seekg(0, ios::beg);
      while (file >> str)
        {
          cout << str << endl;
        }

      file.seekp(0, ios::end);
      file << "end\n";
      file.flush();
      file.close();
    }
  return 0;
}

Строка `end` не запишется. Почему, не как не пойму.

Ответ на: комментарий от hello_world

Судя по всему, так и есть:

cout << file.good() << endl;
file.seekg(0, ios::beg);
while (file >> str)
{
cout << str << endl;
}
cout << file.good() << endl;
file.seekp(0, ios::end);
cout << file.good() << endl;

1
hello
0
0

Spectr ★★★
()
Вы не можете добавлять комментарии в эту тему. Тема перемещена в архив.