Search code examples
cfwrite

fwrite writes garbage value to file


#include <stdio.h>

struct struct_type
{
  int d;
};

int main()
{

  struct struct_type *cust;

  cust->d=13;

  FILE* fp;

  fp = fopen("path to file", "wb+");

  or,

  fp = fopen("path to file", "w+");     

  fwrite(cust, sizeof(struct struct_type), 1, fp);

  fclose(fp);

  return 0;

}

Expected output

13

However getting garbage value written to file.


Solution

  • Assuming you had allocated memory for cust, or used a plain struct instead of a pointer, you'd get a file that contains the binary representation of the int 13 on your platform. Which would be unreadable in, say, notepad.

    If you look at the output in a hex editor, you'll see a few zero bytes and one 0xOD - number of zero bytes depends on the size of ints on your platform, and whether they'll be before or after the 13 byte depends on its endianness.

    If you want a file with 13 as text in it, use fprintf.

    (Since you haven't allocated memory, your program has undefined behavior, and can do anything at all.)


    Fix with a struct on stack:

    #include <stdio.h>
    
    struct struct_type
    {
      int d;
    };
    
    int main()
    {
      struct struct_type cust;
      cust.d=13;
    
      FILE* fp;
      fp = fopen("path_to_file", "wb+");
      fwrite(&cust, sizeof(cust), 1, fp);
      fclose(fp);
    
      return 0;
    }
    
    $ gcc -Wall -std=c99 -pedantic t.c
    $ ./a.out 
    $ hexdump -C path_to_file 
    00000000  0d 00 00 00                                       |....|
    00000004
    

    To get a text file instead, replace the fwrite with:

    fprintf(fp, "%d", cust.d); // or "%d\nd";
    

    and drop the "b" from the open mode since that's for binary I/O.