c++ - 二进制文件中的 C++ Seekp() 正在删除数据
问题描述
我想对二进制文件使用 seekp() 函数来修改某个整数的数据。我制作了简单的测试程序来测试 seekp funstion 但它不起作用,而是删除了文件中的旧内容。
// position in output stream
#include <fstream> // std::ofstream
#include <iostream>
int main() {
std::ofstream outfile{"test.dat" ,std::ios::binary| std::ios::out};
struct t {
int x;
};
t t1{ 36};
t t2{ 2 };
t t3{ 3 };
outfile.seekp(4 , std::ios::beg );
outfile.write((char*)&t1 , sizeof(t1));
outfile.write((char*)&t2, sizeof(t2));
outfile.write((char*)&t3, sizeof(t3));
outfile.close();
std::ifstream iutfile{ "test.dat" ,std::ios::binary };
t read;
while (iutfile.read((char*)&read, sizeof(read)))
{
std::cout << "\n\n\t" << read.x;
}
iutfile.close();
return 0;
}
#这是我测试它的步骤:#
1) 注释 outfile.seekp(4 , std::ios::beg); 在上面的代码中,它将打印文件
2 中的内容)现在取消注释 seekp 行并注释两个 outfile.write() 行,留下一个来测试 seekp 是否放置指针,以便我可以在确切位置写入但是当我这样做时以前的数据丢失了
3)然后我尝试注释所有写入行,使 seekp 行未注释,然后我看到整个文件 cintent 被删除
我做错了什么我无法理解。我试过 seekp(sizeof(int) , std::ios::beg) 但它也不起作用..请帮忙
解决方案
每次打开文件时都会破坏文件的内容,它与seekp
.
std::ios::out
隐含的意思std::ios::trunc
,除非有std::ios::in
或std::ios::app
也有(是的,这是一团糟)。有关标志如何相互工作的详细说明,请参阅cppreference 。
您需要以附加模式打开文件,然后seekp
定位您感兴趣的位置:
std::ofstream outfile{"test.dat" ,std::ios::binary | std::ios::app}; //out is optional
std::ofstream outfile{"test.dat" ,std::ios::binary | std::ios::app | std::ios::out};
推荐阅读
- java - 在 Google App Engine Java 中,实例上的一个线程是否可能干扰另一个线程?
- android - 无法从 android 中的服务获取数据,但在桌面上的网络浏览器中工作正常
- regex - 如何使用正则表达式解析/sed多个字符串
- python - 在matlab中捕获python执行错误
- python - 使用 python 和 selenium 抓取网站的父子条件语句
- python - 如何从 Word2Vec 模型中提取向量进行聚类
- datastax-java-driver - Datastax中分页状态(作为字符串)的格式是什么
- python - 在 Python 中创建多答案测验时遇到问题
- powershell - Get-ADPrincipalGroupMembership 在 Expression 中按我需要的方式工作
- javascript - 试图将 csv 文件解析为对象数组