到达eof后,文件处理无法使用fstream
File handling not working with fstream after reaching eof?
根据您的建议,我已经按照您的建议更改了代码,但当ios::out替换为ios::ate时,仍然存在问题。文件中没有写入任何内容(写入不起作用)。有没有什么方法可以检查下一个比特是否为eof,而不是读取它然后检查它?按照你的建议。有时当我处理文件时,它会显示文件指针的位置为-1,这意味着什么???
代码:
int main ()
{
char p[80];
fstream file("text1.txt",ios::out|ios::in); //if ios::ate is added here it results into infinite loop
cout<<"Starting position of the file is "<<file.tellg()<<endl;
getch();
if(file.is_open())
cout<<"file is openn";
else
cout<<"file is not openn";
getch();
file.seekp(0);
while(file>>p)
{
cout<<p<<endl;
}
file.clear();
cout<<"nThe current position of the file pointer is "<<file.tellg()<<endl;
file.seekp(0);
if(file.eof())
cout<<"n the eofn";
while(file>>p)
{
cout<<p<<endl;
}
file.close();
return 0;
}
输出:
Starting position of the file is 0
file is open
Hello
man
how
are
you
The current position of the file pointer is 21
Hello
man
how
are
you
当这种从文件读取到文件末尾时,会导致设置eof和failbit。之所以设置Failbit,是因为在file.eof()
条件下创建读取循环并不表示下一次读取将是流的末尾。它只是说我们还没有达到eof,所以使用:
while(file.eof())
{
file >> p;
}
最后一次读取可能只是eof,我们将处理未初始化的数据。如果发生这种情况,p内部将不会提取任何字符,并且将设置eof和fail标志。
当使用c++98时,需要使用将故障位重置为false
file.clear();
为了避免读取错误的情况,您应该在条件为while(file >> p)
时从文件中提取字符。我推荐这个或这个关于堆栈溢出的问题。
因此,正确的C++98代码应该是这样的:
while(file >> p)
{
std::count << p << std::endl;
}
file.clear();
file.seekp(0);
while(file >> p)
{
std::count << p << std::endl;
}
file.close();
我在Visual Studio 2013上测试了几次,每次都有效。
考虑ios::ate
模式:ios::out
、ios::in
是说明如何打开有问题的文件的修饰符。若要从文件中读取内容,则需要使用ios::out
标志,而要进行写入,则需要用到ios::in
。
另一方面,ios::ate
只是告诉编译器打开文件并立即转到文件的末尾。所以,若你们用ios::ate
代替ios::out
,那个么写入是不可能的,并且程序将在file << "Hello...";
上升起失败标志。如果您只想附加数据,但从文件的开头读取,则应该使用ios::app
,因为它告诉在每次写入之前查找eof。
- 警告处理为错误这里有什么问题
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 处理多个异常集合的C++方法
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 使用流处理接收到的数据
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 基于多个条件处理地图中的所有元素
- 如何用数字处理log(0)
- 在fstream期间忽略空行
- SSL上的`curl_easy_send`和`curl_asy_recv`:如何处理`CURLE_AGAIN`
- 错误处理.将系统错误代码映射到泛型
- C++ 错误检查 fstream open() 命令和一般字符串流错误处理
- STD :: FSTREAM文件处理重复使用的问题
- fstream和sstream处理:输入重复
- 我是否应该期望在 CentOS6 和 CentOS7 之间处理 fstream 异常时有不同的行为
- 在批处理文件上进行C++fstream写入,然后结束,没有剩余的代码行
- 到达eof后,文件处理无法使用fstream
- fstream打开在处理较大的文件时有问题吗?
- fstream打开时未处理异常