问题
In the following program I am trying to understand how to read and write files.
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
fstream myfile;
string str1;
myfile.open("H:/input_file.txt");
if(myfile.is_open())
{
myfile<<"test1 writing files"<<" ";
myfile>>str1;
cout<<str1<<endl;
}
return 0;
}
Why I don't get any output on the console even though "test1 writing files" is written into a file?
回答1:
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.
来源:https://stackoverflow.com/questions/35836214/why-i-cant-read-from-file-using-file-ptrvariable-in-my-program