zoukankan      html  css  js  c++  java
  • C++详细的错误测试

    核心概念:所有的流对象都有错误状态位,表示流的状态。

    所有流对象都包含一组充当标志的位。这些标志表示流的当前状态。

    文件状态位标志

    位        描述

    ios::eofbit  在遇到输入流结束时设置。

    ios::failbit  当尝试的操作失败时设置。

    ios::hardfail  当发生不可恢复的错误时设置。

    ios::badbit  当试图进行无效操作时进项设置。

    ios::goodbit  当所有上面的标志没有设置时设置。表示流状态良好。

    上述位可以通过以下列出的成员函数进行测试。其中clear()函数可用于设置状态位:

    报告位标志的成员函数

    函数        描述

    eof()    如果设置了eofbit标志,则返回true(非零);否则返回false。

    fail()    如果设置了failbit或hardfail标志,则返回true(非零);否则返回false。

    bad()        如果设置了badbit标志,则返回true(非零);否则返回false。

    good()   如果设置了goodbit标志,则返回true(非零);否则返回false。

    clear()   当不带参数调用时,清楚上面列出的所有标志。也可以用特定的标志作为参数来调用。

    测试代码:

    #include <iostream>
    #include <fstream>
    using namespace std;

    //Function prototype
    void showState(fstream & );

    int main()
    {
      fstream testFile("stuff.dat", ios::out);
      if(testFile.fail())
      {
        cout<<"Cannot open the file. ";
        return 0;
      }
      int num = 0;
      cout<<"Writting to the file. ";
      testFile<<num;
      showState(testFile);
      testFile.close();

      //Open the same file, read the number, show status
      testFile.open("stuff.dat",ios::in);
      if(testFile.fail())
      {
        cout<<"cannot open the file. ";
        return 0;
      }
      cout<<"Reading from the file. ";
      testFile>>num;
      showState(testFile);

      //Attempt an invalid read, and show status
      cout<<"Forcing a bad read operator. ";
      testFile>>num;
      showState(testFile);

      //close file and quit
      testFile.close();
      return 0;
    }


    void showState(fstream &file)
    {
    cout<<"File Status: ";
    cout<<" eof bit: "<<file.eof()<<endl;
    cout<<" fail bit: "<<file.fail()<<endl;
    cout<<" bad bit: "<<file.bad()<<endl;
    cout<<" good bit: "<<file.good()<<endl;
    file.clear(); //清楚所有不良位
    }

    结果:

    为了进行错误描述,一个流对象的行为就像一个布尔表达式,当没有设置错误标志时为true,否则为false。要检查在流数据文件上执行的上一次操作是否成功,可以使用以下语句:

      if(dataFile)

      {

        cout<<"Success!";

      }

      要检查操作是否因某些错误而失败,可以调用fail()成员函数,也可以使用以下语句:

        if(!dataFile)

        {

          cout<<"Failure!";

        }

  • 相关阅读:
    js json字符串与json对象互相转换(最全)
    eclipse 离线安装SVN插件(支持eclipse201909)
    eclipse maven项目如何将所有的jar包复制到lib目录下?
    windows/tomcat 修改java虚拟机JVM以utf-8字符集加载class文件的两种方式
    eclipse 设置所有文件编码为UTF-8(最全)
    控制程序的启动数量(限制游戏多开)
    POJ 1719 Shooting Contest(二分图匹配)
    微信企业号开发:消息类型与差别
    Android
    SSI(Server Side Include)简单介绍
  • 原文地址:https://www.cnblogs.com/ruigelwang/p/12652517.html
Copyright © 2011-2022 走看看