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.

Recommended Answers

All 3 Replies

What does your "garbage value" look like?

What does your "garbage value" look like?

like this: ΒΌ @

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.