C++ 写入数据时 std::ofstream 中的错误处理

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28342660/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 20:57:29  来源:igfitidea点击:

Error handling in std::ofstream while writing data

c++ofstream

提问by Santosh Sahu

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;
 }

My diskspace is very less, and the statement "ofs<" fails. So I know that this is an error logically.

我的磁盘空间非常少,并且语句“ ofs<”失败。所以我知道这在逻辑上是错误的。

The statement "if(!ofs)"does not encounter the above issue, hence I am unable to know why it failed.

语句“if(!ofs)”没有遇到上述问题,因此我不知道它为什么失败。

Please tell me, by which other options I would be able to know that "ofs<has failed.

请告诉我,我可以通过哪些其他选项知道 “ofs<已失败。

Thanks in advance.

提前致谢。

采纳答案by Santosh Sahu

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 hereand thereto check for the correctness.

您也可以在这里那里参考以下链接以检查正确性。

回答by James Kanze

In principle, if there is a write error, badbitshould be set. The error will only be set when the stream actually tries to write, however, so because of buffering, it may be set on a later write than when the error occurs, or even after close. And the bit is “sticky”, so once set, it will stay set.

原则上,如果有写错误,badbit应该设置。错误只会在流实际尝试写入时设置,但是,由于缓冲,它可能会在比发生错误时更晚的写入时设置,甚至在关闭后设置。并且该位是“粘性的”,因此一旦设置,它将保持设置。

Given the above, the usual procedure is to just verify the status of the output after close; when outputting to std::coutor std::cerr, after the final flush. Something like:

鉴于上述情况,通常的程序是在关闭后验证输出的状态;当输出到std::coutor 时std::cerr,在最后一次刷新之后。就像是:

std::ofstream f(...);
//  all sorts of output (usually to the `std::ostream&` in a
//  function).
f.close();
if ( ! f ) {
    //  Error handling.  Most important, do _not_ return 0 from
    //  main, but EXIT_FAILUREl.
}

When outputting to std::cout, replace the f.close()with std::cout.flush()(and of course, if ( ! std::cout )).

当输出到std::cout,更换f.close()std::cout.flush()(当然,if ( ! std::cout ))。

AND: this is standard procedure. A program which has a return code of 0 (or EXIT_SUCCESS) when there is a write error is incorrect.

并且:这是标准程序。EXIT_SUCCESS出现写入错误时返回码为 0(或)的程序是不正确的。