读取和写入同一个文件fstream

Reading and writing to the same file fstream

本文关键字:文件 fstream 同一个 读取      更新时间:2023-10-16

我想更新现有的json文件。

这是json文件的示例:

{
   "Foo": 51.32,
   "Number": 100,
   "Test": "Test1"
}

程序日志:

Operation successfully performed
100
"Test1"
51.32
46.32
Done

看起来everythink工作正常…

如果我将fstream更改为ifstream来读取,然后将ofstream更改为写入,它会正常工作…

我尝试使用调试器,当我看到我有错误的数据在basic_ostream对象…但我不知道为什么,我使用数据从字符串更正(更新的数据)。

你这里有几个问题。

首先,命令json json_data(fs);读取到文件的末尾,设置EOF标志。流将停止工作,直到该标志被清除。

第二,文件指针位于文件末尾。如果您想要覆盖文件,则需要再次移动到开头:

if (fs.is_open())
{
    json json_data(fs); // reads to end of file
    fs.clear(); // clear flag
    fs.seekg(0); // move to beginning

不幸的是,这仍然不能解决所有问题,因为如果您回写的文件小于,则会有一些旧数据标记到新数据的末尾:

    std::cout << "Operation successfully performedn";
    std::cout << json_data.at("Number") << std::endl;
    std::cout << json_data.at("Test") << std::endl;
    std::cout << json_data.at("Foo") << std::endl;
    json_data.at("Foo") = 4.32; // what if new data is smaller?
Json文件:

{
   "Foo": 4.32, // this number is smaller than before
   "Number": 100,
   "Test": "Test1"
}} // whoops trailing character from previous data!!

在这种情况下,我会简单地打开一个文件进行读取,然后打开另一个文件进行写入,这样更不容易出错,并且表达了覆盖所有内容的意图。

类似:

#include "json.hpp"
#include <iostream>
#include <fstream>
#include <string>
using json = nlohmann::json;
void readAndWriteDataToFile(std::string fileName) {
    json json_data;
    // restrict scope of file object (auto-closing raii)
    if(auto fs = std::ifstream(fileName))
    {
        json_data = json::parse(fs);
        std::cout << "Operation successfully performedn";
        std::cout << json_data.at("Number") << std::endl;
        std::cout << json_data.at("Test") << std::endl;
        std::cout << json_data.at("Foo") << std::endl;
    }
    else
    {
        throw std::runtime_error(std::strerror(errno));
    }
    json_data.at("Foo") = 4.32;
    std::cout << json_data.at("Foo") << std::endl;
    std::string json_content = json_data.dump(3);
    if(auto fs = std::ofstream(fileName))
    {
        fs.write(json_content.data(), json_content.size());
        std::cout << "Done" << std::endl;
    }
    else
    {
        throw std::runtime_error(std::strerror(errno));
    }
}
int main()
{
    try
    {
        std::string fileName = "C:/new/json1.json";
        readAndWriteDataToFile(fileName);
    }
    catch(std::exception const& e)
    {
        std::cerr << e.what() << 'n';
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}