[英]Why I can't read from file using “file_ptr>>variable” in my program?
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? 为什么即使将“ test1 Writing files”写入文件,控制台上也没有任何输出?
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). 将需要同时打开文件以进行读取和写入(对不起,请忽略;默认情况下,同时打开fstream进行读取和写入操作)。 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. 写入(并刷新输出)之后,您将需要seekg()
返回文件的开头,或者您将尝试读取最后编写的内容之后的内容,这当然没什么。
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. seekg
用于更改从文件读取(获取)的位置。 seekp
is used to change the position you write (put) to the file. seekp
用于更改您写入(放置)到文件的位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.