Why I can't read from file using “file_ptr>>variable” in my program?

前端 未结 1 1995
难免孤独
难免孤独 2021-01-27 07:31

In the following program I am trying to understand how to read and write files.

#include
#include
using namespace std;
int main         


        
1条回答
  •  别那么骄傲
    2021-01-27 07:48

    The file will need to be opened for both read and write (I'm sorry, ignore that; fstream is opened for both read & write by default). After writing (and flushing the output), you will need to seekg() back to the beginning of the file, or you will just be trying to read what comes after the last thing you wrote, which will of course be nothing.

    myfile<<"test1 writing files"<<" ";
    myfile.flush(); 
    myfile.seekg(0, ios_base::beg);
    myfile>>str1;
    

    seekg is used to change the position you read (get) from the file. seekp is used to change the position you write (put) to the file.

    0 讨论(0)
提交回复
热议问题