0
int main()
{
    ofstream fout("test.txt");
    //suppose I write a line "hello world" into the text file
    getch();
    return 0;
}

when I run the program . after writing the line into the file I don't see any effect in the file .But after the getch() line or finishing the program I can see the written data into my hard disk file . Why this happen . why it needs to terminate or close the file to show effect of the written data into my file.

play store
  • 393
  • 1
  • 5
  • 5
    Have a look at this link http://www.cplusplus.com/reference/ostream/ostream/flush/ The data is buffered before it's written to the file. if you want to write it immediately you should call flush function. – Roya Ghasemzadeh Aug 17 '19 at 11:36
  • 3
    Because buffering, at many levels. – user207421 Aug 17 '19 at 11:37
  • You could introduce a scope and put all the file operations inside its own block by putting an additional { at the beginning of main and a } before getch(); or move the file operations into a separate function. When the ofstream goes out of scope it will close the file for you. The problem in your example is the ofstream does not go out of scope yet when getch() is called. – drescherjm Aug 17 '19 at 12:27

0 Answers0