读取和写入同一个文件fstream
Reading and writing to the same file fstream
我想更新现有的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;
}
相关文章:
- 使用fstream对txt文件中的数字进行循环
- 为什么 fstream 在打开带有格式的文件时会导致分段错误?
- 无法打开 fstream C++文件,即使它与 .cpp 位于同一位置
- 使 std::fstream 写入文件末尾,但从头开始读取
- 如何修复函数中的 fstream 文件输入以将正确的信息存储在结构数组中?
- 如何检查文件是否已存在于 fstream C++中
- 使用 fstream 库并在屏幕上打印的文件有问题?
- Windows std::fstream 修改文件后打开()?
- 如何删除文件中的数字,通过 c++ fstream 的
- 如何使用单个fstream创建、读取和写入文件
- 如何使用fstream从.txt文件C++中取出int值
- fstream库,试图创建一个变量名为(c++)的文件
- 变量 std::fstream 文件具有初始值设定项,但类型不完整 编译错误
- 如何在 c++ 中使用 fstream 读取.txt文件
- 为什么错误"permission denied","id returned 1 exit status"仅在 IM 使用 C++ 中的头文件 fstream 时才出现
- 创建.dat文件 (fstream) c++
- 如何读取特定文件fstream
- 在驱动器c:中按类打开文件fstream类
- 使用库更新文件<fstream>(仅覆盖特定部分)
- 读取和写入同一个文件fstream