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.
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.
An example of what I would like to achieve: Change 3rd byte to 67
Initial file:
00 2F 71 73 76 95
File content after write:
00 2F 67 73 76 95
Use fseek()
to position the file-pointer and then write out 1 byte:
// 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;
}
See http://www.cplusplus.com/reference/cstdio/fseek/
For an existing file and only changing 1 char:
FILE * pFile;
char c = 'a';
pFile = fopen("example.txt", "r+b");
if (pFile != NULL) {
fseek(pFile, 2, SEEK_SET);
fputc(c, pFile);
fclose(pFile);
}
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 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With