7

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

2 Answers 2

7

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

So if I do fseek(file, 3, SEEK_SET); and then fwrite(&buffer, sizeof(char), 1, file);` and buffer holds the value 67, that will get the things done as I want?
Yes, but you could also use fputc(). And your 'file' in fseek() will need to be a pointer.
5

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

2 Comments

Thank you, I thought that after doing something like this the file would hold just 00 2F 67
@Gernot1976 note that sizeof( unsigned char ) is 1 by definition, it would be better to use this to match any change in the variable type written, for example sizeof newbyte

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.