I am trying to overwrite a single byte in a binary file. I am using fseek() to set the stream position indicator to the byte that I want to overwrite. Then I am calling to fwrite() with a new byte in that location. Somehow the other bytes in the file are being affected. Heres some code:
bool x = 1;
bool y = 0;
bool z = 1;
/* WRITE 101 to file */
FILE *ff = fopen(file, "wb");
fwrite(&x, sizeof(x), 1, ff);
fwrite(&y, sizeof(y), 1, ff);
fwrite(&z, sizeof(y), 1, ff);
fclose(ff);
bool x_r, y_r, z_r;
/* READ from file */
ff = fopen(file, "rb");
fread(&x_r, sizeof(x_r), 1, ff);
fread(&y_r, sizeof(y_r), 1, ff);
fread(&z_r, sizeof(z_r), 1, ff);
fclose(ff);
/* PRINT to standard output */
cout << x_r << y_r << z_r << endl; // OUTPUT: 101
bool overwrite = 1;
/* OVERWRITE */
ff = fopen(file, "wb");
fseek(ff, 1, SEEK_SET);
fwrite(&overwrite, sizeof(overwrite),1 , ff);
fclose(ff);
/* READ from file */
ff = fopen(file, "rb");
fread(&x_r, sizeof(x_r), 1, ff);
fread(&y_r, sizeof(y_r), 1, ff);
fread(&z_r, sizeof(z_r), 1, ff);
fclose(ff);
/* PRINT to standard output */
cout << x_r << y_r << z_r << endl; // OUPUT 011; I was expecting 111
The above code basically writes three bytes of data to a file. 101. Then I use fseek() to set to reposition the stream indicator to point to the second byte. But calling fwrite() to overwrite the second byte from 0 to 1 is changing the first byte as well. The expected output is 111, but I am getting 011.
Any ideas why this is happening? I tried putc as well, but that didn’t work out either. Any help would be appreciated.
“r+” mode opens the file for reading and writing, but preserves its contents.