6

I have a file stream open and ready.

How do I access and change a single Byte in the stream such that the change is reflected on the file?

Any suggestions?

Yuval Adam
  • 161,610
  • 92
  • 305
  • 395

3 Answers3

9
#include "stdio.h"

int main(void)
{
    FILE* f = fopen("so-data.dat", "r+b"); // Error checking omitted
    fseek(f, 5, SEEK_SET);
    fwrite("x", 1, 1, f);
    fclose(f);
}
RichieHindle
  • 272,464
  • 47
  • 358
  • 399
  • A (f != NULL) is required. fclose(NULL) invokes UB. – dirkgently May 10 '09 at 11:23
  • fwrite("x", 1, 1, f); Doesn't this write the first byte of the address of the string "x"? –  May 10 '09 at 11:24
  • No, it doesn't - ignore me :-) –  May 10 '09 at 11:25
  • Doesn't the r+ permission disallow writing? – cletus May 10 '09 at 11:26
  • @cletus: Then what "r" is expected to do? "r+" is read/write. – Mehrdad Afshari May 10 '09 at 11:29
  • 3
    Note that jumping to computed locations in a *text* mode file is implementation defined. For a platform where text and binary modes are different (i.e., almost everything except Unix), you'll need to handle the fact that newlines can be multiple bytes (or otherwise funny). Whether this matters to Yuval A I don't know. –  May 10 '09 at 11:56
  • @liw.fi: see also http://stackoverflow.com/questions/229924/difference-between-files-writen-in-binary-and-text-mode ; I'd recommend to always open files in binary mode by default so you can be sure that what you see is what you get – Christoph May 10 '09 at 12:11
5
FILE* fileHandle = fopen("filename", "r+b"); // r+ if you need char mode
fseek(fileHandle, position_of_byte, SEEK_SET);
fwrite("R" /* the value to replace with */, 1, 1, fileHandle);
Mehrdad Afshari
  • 414,610
  • 91
  • 852
  • 789
3
#include <stdio.h> /* standard header, use the angle brackets */

int main(void)
{
    char somechar = 'x'; /* one-byte data */
    FILE* fp = fopen("so-data.txt", "r+");
    if (fp) {
      fseek(fp, 5, SEEK_SET);
      fwrite(&somechar, 1, 1, fp);
      fclose(fp);
    }
    return 0; /* if you are on non-C99 systems */
}
dirkgently
  • 108,024
  • 16
  • 131
  • 187