0

我正在为我的程序编写配置。此配置使用nlohman json以 json 格式存储。我正在使用 std::fstream 将 json 对象写入文件。一切都很好,但过了一会儿我的程序停止写入文件。
这是一个最小的可重现示例:

#include <iostream>

#include <nlohmann/json.hpp>
#include <fstream>
#include <iomanip>

bool load(std::fstream &config_fs) {
    if (config_fs) {
        try {
            nlohmann::json json;
            config_fs >> json;
            std::cout << json << std::endl;
            return true;
        } catch (std::exception &e) {
            std::cout << "54 " << (bool)config_fs << std::endl; // 1
            std::cout << "Cannot load config: " << e.what() << std::endl;
            return false;
        }
    }
    std::cout << "Cannot load config because file is not open" << std::endl;
    return false;
}

bool save(std::fstream &config_fs) {
    std::cout <<  "37 " << (bool)config_fs << std::endl;
    if (config_fs) {
        nlohmann::json json{{"test", 42}};
        std::cout <<  "39 " << (bool)config_fs << " " << config_fs.is_open() << " " << strerror(errno) << std::endl;
        config_fs << std::setw(4) << json << std::endl;
        std::cout <<  "41 " << (bool)config_fs << " " << config_fs.is_open() << " " << strerror(errno) << std::endl;
        return true;
    }
    std::cout << "Cannot save config because file is not open" << std::endl;
    return false;
}

int main() {
    std::string config_file = "../config_test.json";
    std::fstream config_fs(config_file, std::ios::in | std::ios::out);
    if (!config_fs) {
        std::cout << "Cannot open configuration file " << config_file <<  ", creating it" << std::endl;
        config_fs.open(config_file, std::ios::out);
        if (!config_fs) {
            std::cout << "Cannot create config file " << config_file << std::endl;
        } else {
            config_fs.close();
            config_fs.open(config_file, std::ios::in | std::ios::out);
        }
    }
    if(!load(config_fs)) {
        std::cout << "Cannot load config from " << config_file << ", putting default values" << std::endl;
        std::cout << "21 " << (bool)config_fs << std::endl;
        save(config_fs);
    }

    return 0;
}

这是程序的输出:

54 1
Cannot load config: [json.exception.parse_error.101] parse error at line 1, column 1: syntax error while parsing value - unexpected end of input; expected '[', '{', or a literal
Cannot load config from ../config_test.json, putting default values
21 1
37 1
39 1 1 Success
41 0 1 Success

这意味着在我使用Successerrno 进行写入尝试后 fstream 关​​闭并且文件保持为空!我不知道是什么导致了这种行为。我也找不到任何类似的问题,我对此感到非常困惑。
请指出我,这个问题的原因是什么。
谢谢!

UPD:为 fstream 启用异常后'std::ios_base::failure[abi:cxx11]' what(): basic_ios::clear: iostream error引发异常output_stream_adapter::write_characters(const CharType* s, std::size_t length)config_fs.exceptions(std::ios::badbit | std::ios::failbit);

4

0 回答 0