fstream操作为ios :: out模式设置failbit

时间:2017-12-20 01:28:27

标签: c++ ios fstream

对于类构造函数中的以下简单测试代码:

//test_code.hpp
#ifndef TST_CDE_H
#define TST_CDE_H
#include<numeric>
#include<random>
#include<algorithm>
#include<iterator>
#include<fstream>
using std::ios;
using std::ofstream;
using std::vector;
using std::iota;
using std::random_device;
using std::mt19937;
using std::shuffle;

#define FILENAME "DB_file.txt"
#define MAX_ELEMS 1000

class xRan{
public:
xRan();
private:
random_device rd;
};//end of class declaration 
#endif

//test_code.cpp
#include "test_code.hpp"

xRan::xRan(){
vector<int>v(MAX_ELEMS);
mt19937 g(rd());
auto mode = ios::out | ios::app | ios::trunc;
ofstream fs(FILENAME,mode);
if(fs.good()){
iota(v.begin(),v.end(),1);
shuffle(v.begin(),v.end(),g);
std::copy(v.begin(),v.end(),std::ostream_iterator<int>(fs, " "));
fs.close();
}
}//end of constructor defintion

//test_main.cpp
#include "test_code.hpp"

int main(){
xRan rand_obj;
return 0;
}//end of main()

在输出模式下打开文本文件并写入文件文件的fstream操作,在fstream上设置ios :: failbit。

Debugging using gdb gives the following steps:
(gdb) n
6   auto mode = ios::out | ios::app | ios::trunc;
(gdb) n
7   ofstream fs(FILENAME,mode);
(gdb) n
1219    {
(gdb) n
336     ios_base() {// purposefully does no initialization
(gdb) n
648     basic_ios() {// purposefully does no initialization
(gdb) n
1219    {
(gdb) n
1218        : basic_ostream<char_type, traits_type>(&__sb_)
(gdb) n
165     { this->init(__sb); }
(gdb) n
685     ios_base::init(__sb);
(gdb) n
686     __tie_ = 0;
(gdb) n
687     __fill_ = traits_type::eof();
(gdb) n
1219    {
(gdb) n
1177        explicit basic_ofstream(const char* __s, ios_base::openmode __mode = ios_base::out);
(gdb) n
1220        if (__sb_.open(__s, __mode | ios_base::out) == 0)
(gdb) n
1221            this->setstate(ios_base::failbit);
(gdb) n

根据代码为什么尝试在输出模式下打开文本文件会在fstream上设置ios :: failbit?

非常感谢您的建议。

TIA VIN

0 个答案:

没有答案