C ++,同时读取和写入二进制文件 [英] C++, read and write to a binary file at the same time

查看:184
本文介绍了C ++,同时读取和写入二进制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hi
我想知道是否可以从fstream的二进制文件中读取一个字节,然后更改该字节并将其写回。
我试过这个代码,但它没有工作,没有发生,但我确定它读取正确。

Hi I wanted to know if it's possible to read a byte from a binary file with "fstream" and then change that byte and write it back. I tried this code but it didn't work and nothing happens but I'm sure it reads correctly.

file.open(path, ios::in|ios::out|ios::binary|ios::ate);
file.seekg(0, ios::end);
int size=file.tellg();
file.seekg(0,ios::beg);
char buffer;    
for(int i=0;i<size;i++)
{
    file.read((char*)&buffer,sizeof(char));
    buffer=(buffer+7)%256;
    file.write((char*)&buffer, sizeof(char));
}

我应该读取文件指针一个字节回读如下: p>

should I take the file pointer one byte back after reading like this:

file.seekg(-1, ios::cur);

提前感谢。

推荐答案

是的。正如您在问题中建议的,如果要覆盖先前读取的字节,则需要使用seekg调整文件指针的位置。每次读取后,文件指针将位于读取的字节之后。

Yes. As you suggested in the question, you need to adjust the position of the file pointer using seekg if you want to overwrite the previously read bytes. After each read, the file pointer would be positioned after the read bytes.

这篇关于C ++,同时读取和写入二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆