Search code examples
cstringbinaryfilesfread

Writing strings to binary files in C


I have some code that writes a char * to a binary file like so:

FILE *fp = fopen(path, "wb");
if (fp == NULL) {
    printf("Failed to open file at path: %s. %s\n", path, __PRETTY_FUNCTION__);
    return;
}

fwrite("Hello", 6, 1, fp);

The problem is that when I then read from that file like so:

FILE *fp = fopen(path, "rb");
if (fp == NULL) {
    printf("Failed to open file at path: %s. %s\n", path, __PRETTY_FUNCTION__);
    return;
}


char *str;
fread(str, 6, 1, fp);
printf("Got str: %s\n", str);

I get different results e.g. Oello or Mello. What is going on?


Solution

  • This code is incorrect:

    char *str;
    fread(str, 6, 1, fp);
    printf("Got str: %s\n", str);
    

    char *str; creates an uninitialized character pointer. Where's the memory that it points to?

    char str[ 7 ];
    fread(str, sizeof( str ) - 1, 1, fp);
    str[ sizeof( str ) - 1 ] = '\0';
    printf("Got str: %s\n", str);
    

    would be better, although it still doesn't check the return value from fread() to ensure data is actually read.