[英]How to read back what I just wrote to a file?
我一直在尝试编写一个程序来以读写模式打开文件:
#include <fstream>
#include <iostream>
using namespace std;
int main(){
fstream obj;
obj.open("hello.txt",ios::in|ios::out);
if (!obj){
cout << "File not opened" <<endl;
return 1;
}
obj << "Hi How are you" ;
char c;
while (!obj.eof()){
obj.get(c);
cout << c;
}
obj.close();
return 0;
}
当我在 Windows 上的 Visual Studio Code 上编译这个程序时,虽然文件中打印了文本“你好,你好吗”,但文件的内容并没有打印在我的屏幕上。 有人可以告诉我可能是什么问题吗?
使用 seekp 将seekp
指示器重置为 0 会有所帮助,因为 output 和输入指示器都在写入操作后设置到文件末尾(您可以使用tellp
tellg
读取它们)。
obj << "Hi How are you" ;
obj.seekp(0);
char c;
while (!obj.eof()){
obj.get(c);
cout << c;
}
考虑避免使用obj.eof()
,您可以例如逐行读取文件:
std::string line;
std::getline(obj, line);
std::cout << line << std::endl;
或在循环中:
while (std::getline(obj, line)) // here std::basic_ios<CharT,Traits>::operator bool is used to check if operation succeeded
{
std::cout << line << std::endl;
}
你有两个问题:缓冲和寻找 position。
缓冲:当您使用obj << "Hi How are you
写入文本时,您只需将其写入缓冲区,然后在刷新缓冲区后将文本写入文件。您可以调整要使用的缓冲区类型。最简单如果使用行缓冲,方法是在文本之后写入std::endl
。
更好的解释已经在这里
求 Position:
您正在从文件中的最后一个 position 读取。 您必须手动将读取的 position 更改为文件中的第一个字符,然后您就完成了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.