这是示例Json文件:
{ "Foo": 51.32,"Number": 100,"Test": "Test1"}
来自程序的日志:
Operation successfully performed100"Test1"51.3246.32Done
看起来Everythink按预期工作……
如果我将fstream更改为ifstream以便读取,并且稍后将其更改为写入它的工作…
我尝试使用调试器,因为我看到我在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 performed\n"; 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 performed\n"; 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;}总结
以上是内存溢出为你收集整理的c – 读取和写入同一文件fstream全部内容,希望文章能够帮你解决c – 读取和写入同一文件fstream所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)