修改C中二进制文件中的一些字节

有没有办法改变二进制文件中单个字节的值? 我知道如果你以r+b模式打开文件,光标位于现有文件的开头,你在该文件中写入的任何内容都将覆盖现有内容。

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

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

初始档案:

 00 2F 71 73 76 95 

写入后的文件内容:

 00 2F 67 73 76 95 

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

 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 ); 

使用fseek()定位文件指针 ,然后写出1个字节:

 // fseek example #include  int main () { FILE * pFile; pFile = fopen("example.txt", "wb"); fputs("This is an apple.", pFile); fseek(pFile, 9, SEEK_SET); fputs(" sam", pFile); fclose(pFile); return 0; } 

见http://www.cplusplus.com/reference/cstdio/fseek/

对于现有文件 ,仅更改1个字符:

 FILE * pFile; char c = 'a'; pFile = fopen("example.txt", "r+b"); if (pFile != NULL) { fseek(pFile, 2, SEEK_SET); fputc(c, pFile); fclose(pFile); }