C/copying a c structure in a file created in c
Expert: Narendra - 10/25/2007
Questionhi,
am unable to copy the following structure in a file created in c
struct temp
{
char fname[10];
int size;
char type [10];
}tmp;
and the code for copying in c file is
#include<stdio.h>
#include<string.h>
#include "temp.h"
FILE *fp,*fpp;
int main()
{
tmp t1;
int size=sizeof(t1);
fp=fopen("config.txt","w");
strcpy(t1.fname,"movie\n");
t1.size=1;
strcpy(t1.type,"\nvideo\n");
fflush(fp);
/*fprintf("%s",t1.fname);
fprintf("%d", t1.size);
fprintf(fp,"%s",t1.type);*/
fwrite(&t1,sizeof(t1),1,fp);
fflush(fp);
fclose(fp);
//fflush(fp);
return 0;
}
it can be done by copying the inividual fields as done with fprintf but i will ve a huge structure actually.
now the errors are
1> it also copies the blank spaces in the two char fields and throwinf garbage in file which is not desired
2>it converts the int field to ascii char and writing in file and hence for 0-64 and 123-rest is converted to garbage.
now can u suggest some alter.am workin in linux platform.
pls reply to arsam13@gmail.com
AnswerYou are using both fwrite() and fprintf() to write to file.
Both work in different way.
While fprintf() writes with the format that you provide, fwrite() writes raw data (this is what you are calling garbage).
So, use only fprintf(), if you want to open the file in an editor and read the contents as you want.