I'm Using fwrite to print the contents of a sturcture in a file.

#include <stdio.h>
#include <stdlib.h>

struct com{
           int code;
           char* name;

int main()
struct com py[2]={{21,"Monty Python"},
		  {22,"Python lang"}
FILE * fp;
fwrite(&py,sizeof(struct com),1,fp);
/*int i;
return 0;


It either prints nothing or prints some garbage.
While the second method using fprintf() seems to work.

Edited 5 Years Ago by D33wakar: n/a

While the second method using fprintf() seems to work.

fprintf() and fwrite() do completely different things. fprintf() converts values into their textual representation while fwrite() just dumps the bytes of the value to a stream without any kind of conversion. Your garbage is perfectly understandable as the contents of the structure are an integer and a pointer, both of which don't have a meaningful text representation when written byte-by-byte.

Even worse is that you're trying to serialize an address, which almost certainly won't be valid when reading from the file. In this case your best option is to use a text conversion of the structure or an intermediate format that won't mangle your data.

This article has been dead for over six months. Start a new discussion instead.