当前位置:  开发笔记 > 编程语言 > 正文

即使没有错误,std :: ifstream设置失败()

如何解决《即使没有错误,std::ifstream设置失败()》经验,为你挑选了1个好方法。

在Cygwin 1.7.24上使用GCC 4.7.3.编译器选项包括:-std = gnu ++ 11 -Wall -Wextra

我正在使用命令行应用程序,我需要能够加载并保存一组字符串,因此我在std :: set周围编写了一个快速包装类来添加加载和保存方法.

// KeySet.h

#ifndef KEYSET_H
#define KEYSET_H

#include 
#include 
#include 
#include 

#include 
#include 
#include 
#include 

inline bool file_exists (const std::string& filename)
{
/*
    Utility routine to check existance of a file.  Returns true or false,
    prints an error and exits with status 2 on an error.
*/
    struct  stat buffer;
    int     error = stat(filename.c_str(), &buffer);
    if (error == 0) return true;
    if (errno == ENOENT) return false;
    std::cerr << "Error while checking for '" << filename << "': " << strerror(errno) << std::endl;
    exit (2);
}

class KeySet
{
private:
    std::string             filename;
    std::set   keys;

public:
    KeySet() {}
    KeySet(const std::string Pfilename) : filename(Pfilename) {}

    void set_filename (const std::string Pfilename) {filename = Pfilename;}
    std::string get_filename () {return filename;}
    auto size () -> decltype(keys.size()) {return keys.size();}
    auto cbegin() -> decltype(keys.cbegin()) {return keys.cbegin();}
    auto cend() -> decltype(keys.cend()) {return keys.cend();}
    auto insert(const std::string key) -> decltype(keys.insert(key)) {return keys.insert(key);}
    void load ();
    void save ();
};

void KeySet::load ()
{
    if (file_exists(filename)) {
        errno = 0;
        std::ifstream   in (filename, std::ios_base::in);

        if (in.fail()) {
            std::cerr << "Error opening '" << filename << "' for reading: " << strerror(errno) << std::endl;
            exit (2);
        }

        std::string     token;
        if (token.capacity() < 32) token.reserve(32);

        while (in >> token) keys.insert(token);

        if (!in.eof()) {
            std::cerr << "Error reading '" << filename << "': " << strerror(errno) << std::endl;
            exit (2);
        }

        in.clear(); // need to clear flags before calling close
        in.close();
        if (in.fail()) {
            std::cerr << "Error closing '" << filename << "': " << strerror(errno) << std::endl;

            exit (2);
        }
    }
}

void KeySet::save ()
{
    errno = 0;
    std::ofstream   out (filename, std::ios_base::out);

    if (out.fail()) {
        std::cerr << "Error opening '" << filename << "' for writing: " << strerror(errno) << std::endl;
        exit (2);
    }

    for (auto key = keys.cbegin(), end = keys.cend(); key != end; ++key) {
        out << *key << std::endl;
    }

    out.close();
    if (out.fail()) {
        std::cerr << "Error writing '" << filename << "': " << strerror(errno) << std::endl;
        exit (2);
    }
}

#endif

//

这是一个测试加载方法的快速程序.

// ks_test.cpp

#include "KeySet.h"

int main()
{
    KeySet          test;
    std::string     filename = "foo.keys.txt";

    test.set_filename(filename);

    test.load();

    for (auto key = test.cbegin(), end = test.cend(); key != end; ++key) {
        std::cout << *key << std::endl;
    }
}

数据文件中只有"一二三".

当我去运行测试程序时,我的测试程序出现以下错误:

$ ./ks_test
Error closing 'foo.keys.txt': No error

无论cppreference.com和cplusplus.com说,close方法应设置错误失败位.save方法工作正常,如果我在关闭后注释掉错误检查,则加载方法可以正常工作.这真的有用还是我误解了它应该有多接近?提前致谢.

编辑澄清,修复拼写错误并根据Joachim Pileborg和Konrad Rudolph的评论调整代码.

编辑为代码添加解决方案.



1> Some program..:

这里有两个错误:第一个是关于你如何阅读,更具体地说是阅读循环.您尝试读取并且读取失败之后eof才会设置该标志.相反,你应该这样做:

while (in >> token) { ... }

否则,您将循环一次到多次并尝试读取超出文件末尾的时间.

第二个问题是你注意到的问题,这取决于第一个问题.由于您尝试读取超出文件末尾的内容,因此即使没有真正的错误,流也会设置failbit导致in.fail()返回true.

推荐阅读
刘美娥94662
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有