zehra.mb@[EMAIL PROTECTED]
schrieb:
> Hi,
> I had written application for storing employee data in binary file and
> reading those data from binary file and display it in C language.
> But I face some issue with writing data to binary file.
> Here is my part of my code.
>
> struct cust_data
> {
> int nCAFID;
> char *szFirstName;
> };
>
> typedef struct cust_data CUST_DATA;
> CUST_DATA *pCustdata = NULL;
> int AddRecord()
> {
> FILE *fp;
> fp = fopen("Input.dat","ab+");
> return fp;
> pCustdata = malloc(sizeof(CUST_DATA));
>
> pCustData->szFirstName = malloc(sizeof(pCustData-
>> szFirstName));
This won't work. sizeof(szFirstName) is the size of the pointer, not the
size
of the string. How should the program know the size of the string without
actually
reading it first? (-;
> printf("Enter CAFID : ");
> scanf("%d",&pCustData->nCAFID);
>
> printf("Enter First Name : ");
> scanf("%s",pCustData->szFirstName);
>
> fwrite(pCustData,sizeof(CUST_DATA),1,fp);
This is a bad idea for two reasons: First, it *only* writes the structure,
but not the string pointed to by the structure, it also writes a binary
pointer to
the file, which is useless the time you re-read it. And second, it writes
the
structure as binary, which is non-****table, and might not work, not even
on the same machine,
using a different compiler, or the same compiler with different options,
etc...
> now here when i write a structure to file, it writes nCAFID and
> inplace of szFirstName it writes pointer to string.
> But i need to write string..
Hint: Write the number out as decimal ASCII (which is ****table), write out
the string
as string, which is also ****table. Don't try to write out the entire
struct as
binary blob, but rather write two functions, potentially named "serialize"
and "deserialize" which
take the structure and write it out to a file, or read it from a file.
So long,
Thomas
--
comp.lang.c.moderated - moderation address: clcm@[EMAIL PROTECTED]
-- you must
have an appropriate newsgroups line in your header for your mail to be
seen,
or the newsgroup name in square brackets in the subject line. Sorry.


|