在C中修改二进制文件中的某些字节 [英] Modify some bytes in a binary file in C

查看:210
本文介绍了在C中修改二进制文件中的某些字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以更改二进制文件中单个字节的值?我知道,如果您以 r + b 模式打开文件,则光标将位于现有文件的开头,并且您在该文件中写入的所有内容都会覆盖现有内容

Is there any way to change the value of a single byte in a binary file? I know that if you open the file in r+b mode, the cursor is positioned at the beginning of the existing file and anything you write in that file will overwrite the existing content.

但是我只想更改文件中的1个字节。我想您可以复制不应修改的文件内容,并在正确的位置插入所需的值,但是我想知道是否还有其他方法。

But I want to change only 1 byte, for instance, in a file. I guess you could copy the content of the file that should not be modified and insert the desired value at the right place, but I wonder if there is any other way.

我要实现的示例:
将第3个字节更改为67

An example of what I would like to achieve: Change 3rd byte to 67

初始文件:

00 2F 71 73 76 95

写入后的文件内容:

00 2F 67 73 76 95


推荐答案

使用 fseek 移动到文件中的位置:

Use fseek to move to a position in a file:

FILE *f = fopen( "file.name", "r+b" );
fseek( f, 3, SEEK_SET ); // move to offest 3 from begin of file
unsigned char newByte = 0x67;
fwrite( &newByte, sizeof( newByte ), 1, f );
fclose( f );

这篇关于在C中修改二进制文件中的某些字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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