You are here:

C/copying a c structure in a file created in c

Advertisement


Question
hi,
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

Answer
You 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.

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Narendra

Expertise

I can answer questions in C related to programming, data structures, pointers and file manipulation. I use Solaris for doing C code and if you have questions related to C programming on Solaris, I will be able to help better.

Experience

6.5

Organizations belong to
Sun Microsystems

Awards and Honors
Brain Bench Certified Expert C programmer.
Advanced System Software Certified

©2012 About.com, a part of The New York Times Company. All rights reserved.