0

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;
if((fp=fopen("data.txt","w+"))==NULL)
    exit(1);
fwrite(&py,sizeof(struct com),1,fp);
/*int i;
for(i=0;i<2;i++)
    fprintf(fp,"code:%d,name:%s\n",py[i].code,py[i].name);
*/
fclose(fp);
return 0;

}

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

Edited by D33wakar: n/a

3
Contributors
3
Replies
4
Views
5 Years
Discussion Span
Last Post by Narue
0

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 topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.