我有一个二进制文件,假设在字节11到字节14,代表一个整数= 100。现在我想替换整数值= 200,而不是现有的一个。我怎么能用C++来做呢?谢谢T。
jv4diomz1#
Google是你的朋友。搜索“C++二进制文件”会给你给予一些有用的页面,比如:This useful link简而言之,你可以这样做:
int main() { int x; streampos pos; ifstream infile; infile.open("silly.dat", ios::binary | ios::in); infile.seekp(243, ios::beg); // move 243 bytes into the file infile.read(&x, sizeof(x)); pos = infile.tellg(); cout << "The file pointer is now at location " << pos << endl; infile.seekp(0,ios::end); // seek to the end of the file infile.seekp(-10, ios::cur); // back up 10 bytes infile.close(); }
int main()
{
int x;
streampos pos;
ifstream infile;
infile.open("silly.dat", ios::binary | ios::in);
infile.seekp(243, ios::beg); // move 243 bytes into the file
infile.read(&x, sizeof(x));
pos = infile.tellg();
cout << "The file pointer is now at location " << pos << endl;
infile.seekp(0,ios::end); // seek to the end of the file
infile.seekp(-10, ios::cur); // back up 10 bytes
infile.close();
}
字符串这适用于阅读。要打开文件进行输出:
ofstream outfile;outfile.open("junk.dat", ios::binary | ios::out);
ofstream outfile;
outfile.open("junk.dat", ios::binary | ios::out);
型结合这两个和调整您的特定需求应该不会太难。
ffvjumwh2#
这个过程有点棘手。让我在代码片段和注解的帮助下写下所需的步骤:
// Open a file to write. Use both ios::out and ios::in. If you dont // use ios::in then file will get truncated. fstream outputfile("data.dat", std::ios::binary | std::ios::out | ios::in ); if(outputfile.is_open()) { int value{200}; //value to be written outputfile.seekp(10); //As we desired to overwrite from 11th byte outputfile.write((char*)(&value), sizeof(int)); //4 bytes will be replaced outputfile.close(); }
// Open a file to write. Use both ios::out and ios::in. If you dont
// use ios::in then file will get truncated.
fstream outputfile("data.dat", std::ios::binary | std::ios::out | ios::in );
if(outputfile.is_open())
int value{200}; //value to be written
outputfile.seekp(10); //As we desired to overwrite from 11th byte
outputfile.write((char*)(&value), sizeof(int)); //4 bytes will be replaced
outputfile.close();
字符串
**注意:**请确保在打开文件时不要使用std::ios::app模式,否则所有的写操作都会被添加到文件的末尾(尾部)。
std::ios::app
2条答案
按热度按时间jv4diomz1#
Google是你的朋友。搜索“C++二进制文件”会给你给予一些有用的页面,比如:This useful link
简而言之,你可以这样做:
字符串
这适用于阅读。要打开文件进行输出:
型
结合这两个和调整您的特定需求应该不会太难。
ffvjumwh2#
这个过程有点棘手。让我在代码片段和注解的帮助下写下所需的步骤:
字符串
**注意:**请确保在打开文件时不要使用
std::ios::app
模式,否则所有的写操作都会被添加到文件的末尾(尾部)。