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

Modify some bytes in a binary file in C

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

但我只想更改文件中的 1 个字节。我想你可以复制文件中不应该修改的内容,然后在正确的地方插入想要的值,但我想知道是否有其他方法。

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

初始文件:

00 2F 71 73 76 95

写入后的文件内容:

00 2F 67 73 76 95

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

// fseek example
#include <stdio.h>

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

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