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

Pol*_*olb 5 c byte file

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

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

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

初始档案:

00 2F 71 73 76 95
Run Code Online (Sandbox Code Playgroud)

写入后的文件内容:

00 2F 67 73 76 95
Run Code Online (Sandbox Code Playgroud)

Dan*_*_ds 6

使用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;
}
Run Code Online (Sandbox Code Playgroud)

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);
}
Run Code Online (Sandbox Code Playgroud)


Rab*_*d76 5

使用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 );
Run Code Online (Sandbox Code Playgroud)

  • @ Gernot1976注意到`sizeof(unsigned char)`的定义是`1`,最好用它来匹配写入的变量类型的任何变化,例如`sizeof newbyte` (2认同)