写入数据时在std :: ofstream中进行错误处理 [英] Error handling in std::ofstream while writing data
本文介绍了写入数据时在std :: ofstream中进行错误处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个小程序,我在其中初始化字符串并写入文件流:
I have a small program where i initialize a string and write to a file stream:
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
std::ofstream ofs(file.c_str());
string s="Hello how are you";
if(ofs)
ofs<<s;
if(!ofs)
{
cout<<"Writing to file failed"<<endl;
}
return 0;
}
我的磁盘空间非常小,并且语句" ofs "失败.所以我从逻辑上知道这是一个错误.
My diskspace is very less, and the statement "ofs<" fails. So I know that this is an error logically.
语句"if(!ofs)" 没有遇到上述问题,因此我不知道为什么失败.
The statement "if(!ofs)" does not encounter the above issue, hence I am unable to know why it failed.
请告诉我,通过哪些其他选项我可以知道"ofs 失败了.
Please tell me, by which other options I would be able to know that "ofs< has failed.
提前谢谢.
推荐答案
我找到了类似的解决方案
I found a solution like
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
std::ofstream ofs(file.c_str());
string s="Hello how are you";
if(ofs)
ofs<<s;
if(ofs.bad()) //bad() function will check for badbit
{
cout<<"Writing to file failed"<<endl;
}
return 0;
}
您还可以参考以下链接那里检查正确性.
You can also refer to the below links here and thereto check for the correctness.
这篇关于写入数据时在std :: ofstream中进行错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文