473,507 Members | 6,727 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problem in writing structure to Binary file in C lang

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));
printf("Enter CAFID : ");
scanf("%d",&pCustData->nCAFID);

printf("Enter First Name : ");
scanf("%s",pCustData->szFirstName);

fwrite(pCustData,sizeof(CUST_DATA),1,fp);

fclose(fp);

free(pCustData->szFirstName);
free(pCustData)
}

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..
if i take szFirstName as char array then it is wroking fine.....but i
want to use heap memory instead of stack..
can anyone help me..................??
thanks in advance.............
Jun 27 '08 #1
5 3793
ze******@gmail.com said:
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+");
What if it fails?
return fp;
Oops - fp is not an int. (I suspect this is simply accidental or forgotten
code.)
pCustdata = malloc(sizeof(CUST_DATA));
What if it fails?
>
pCustData->szFirstName = malloc(sizeof(pCustData-
>>szFirstName));
This will allocate enough bytes to store a pointer, which isn't what you
want. Decide how many bytes to allocate for storing a first name and
allocate that many, or simply make szFirstName an array of char and drop
the szFirstName malloc completely.
printf("Enter CAFID : ");
scanf("%d",&pCustData->nCAFID);

printf("Enter First Name : ");
scanf("%s",pCustData->szFirstName);
You run the risk of having your user enter (accidentally or maliciously)
more characters than you can store, resulting in a buffer overrun.
>
fwrite(pCustData,sizeof(CUST_DATA),1,fp);
This won't work if you dynamically allocate szFirstName - you'd have to
write it separately and make a note of the size so that you can read it
back in. Making szFirstName an ordinary array will fix this.
--
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Jun 27 '08 #2
ze******@gmail.com wrote:
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.
That's usually not a good idea since then you probably won't be
able to read in that file on a machine with a different archi-
tecture and maybe even when you compile the program with a dif-
ferent compiler (or compiler version or options) on the same
machine! Moreover, you run into problems if the struture contains
pointers, as you already found out.
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));
Here you already have a problem. You allocate just enough memory
to store a pointer, but rather likely not enough memory to store
a string (unless it's a very short one).
printf("Enter CAFID : ");
scanf("%d",&pCustData->nCAFID);
printf("Enter First Name : ");
scanf("%s",pCustData->szFirstName);
And if the string the user entered is longer that the size of a
pointer to a string then you write over memory yiu don't own.
If you're lucky you will get an immediate segmentation fault
bur if you're unlucky the program will look as if it's working
and crash in some seemingly unrelated place.

Just some hint: using scanf() this way is inherently unsafe.
This way the user can always enter a string that's longer
than you allocated. If you use scanf() then you will have
to specify a maximum length of the string to be read in to
avoid that (just put the number between the '%' and the 's'
or put a '*' in between and make the maximum number of
characters the next argument of scanf()).
fwrite(pCustData,sizeof(CUST_DATA),1,fp);
fclose(fp);
free(pCustData->szFirstName);
free(pCustData)
}
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..
if i take szFirstName as char array then it is wroking fine.....but i
want to use heap memory instead of stack..
It's not something related to "stack" or "heap" memory. The
problem is that you write just a pointer to the file. And that
pointer value only makes sense while the program that writes
out the structure is still running and hasn't deallocated the
memory the pointer points to. Once the memory has been de-
allocated or when you try to read in the structure with a
new instance of the program (or a different one) the pointer
points to some memory location where there are just random
data (or may even point to memory you're not allowed to
access).

Trying to store a pointer to something instead of the real
thing is like putting a foto of your birthday cake into the
fridge and throwing the cake away. While that may safe some
room in the fridge don't be surprised if the foto doen't
taste as well as the real cake;-)

Actually, if it would be possible to just store pointers
and still get back what they were pointing to you wouldn't
have to store the structure but you could instead just store
the pointer to the structure itself.

So the only reasonable way to write out a structure to a file
is to "serialize" its data. Instead of simply writing out the
structure to a binary file write it's contents in e.g. ASCII,
i.e. first a line with the 'nCAFID' number, then another one
with the string. Only that will allow you to get back the data
in all possible circumstances.

Regards, Jens
--
\ Jens Thoms Toerring ___ jt@toerring.de
\__________________________ http://toerring.de
Jun 27 '08 #3
On Apr 18, 3:22 pm, Richard Heathfield <r...@see.sig.invalidwrote:

Thaks a lot for the reply..
zehra...@gmail.com said:
Hi,
I had written application for storing employee data inbinaryfileand
reading those data frombinaryfileand display it inClanguage.
But I face some issue withwritingdata tobinaryfile.
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+");

What if it fails?
return fp;

Oops - fp is not an int. (I suspect this is simply accidental or forgotten
code.)
sorry thats my mistake..my code is like
if(!fp)
return 0;
pCustdata = malloc(sizeof(CUST_DATA));

What if it fails?
pCustData->szFirstName = malloc(sizeof(pCustData-
>szFirstName));

This will allocate enough bytes to store a pointer, which isn't what you
want. Decide how many bytes to allocate for storing a first name and
allocate that many, or simply make szFirstName an array of char and drop
the szFirstName malloc completely.
printf("Enter CAFID : ");
scanf("%d",&pCustData->nCAFID);
printf("Enter First Name : ");
scanf("%s",pCustData->szFirstName);

You run the risk of having your user enter (accidentally or maliciously)
more characters than you can store, resulting in a buffer overrun.
fwrite(pCustData,sizeof(CUST_DATA),1,fp);

This won't work if you dynamically allocate szFirstName - you'd have to
write it separately and make a note of the size so that you can read it
back in. Making szFirstName an ordinary array will fix this.
ya thats true.
As i mentioned it works fine if i take simple array of characters..
I found what is the problem.Here i am writing pointer to strig in file
and after using the structure i am deaalocation memory for it.
so next time when it reads from a file and try to get value at that
pointer,it wont get the actual data.
so may be i need to serialize the data.

Regards,
Zehra
--
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Jun 27 '08 #4
On Apr 21, 9:26 am, zehra...@gmail.com wrote:
On Apr 18, 3:22 pm, Richard Heathfield <r...@see.sig.invalidwrote:

Thaks a lot for the reply..
zehra...@gmail.com said:
Hi,
I had written application for storing employeedatainbinaryfileand
reading thosedatafrombinaryfileand display it inClanguage.
But I face some issue withwritingdata tobinaryfile.
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+");
What if it fails?
return fp;
Oops - fp is not an int. (I suspect this is simply accidental or forgotten
code.)

sorry thats my mistake..my code is like
if(!fp)
return 0;
pCustdata = malloc(sizeof(CUST_DATA));
What if it fails?
pCustData->szFirstName = malloc(sizeof(pCustData-
>>szFirstName));
This will allocate enough bytes to store a pointer, which isn't what you
want. Decide how many bytes to allocate for storing a first name and
allocate that many, or simply make szFirstName an array of char and drop
the szFirstName malloc completely.
printf("Enter CAFID : ");
scanf("%d",&pCustData->nCAFID);
printf("Enter First Name : ");
scanf("%s",pCustData->szFirstName);
You run the risk of having your user enter (accidentally or maliciously)
more characters than you can store, resulting in a buffer overrun.
fwrite(pCustData,sizeof(CUST_DATA),1,fp);
This won't work if you dynamically allocate szFirstName - you'd have to
write it separately and make a note of the size so that you can read it
back in. Making szFirstName an ordinary array will fix this.

ya thats true.
As i mentioned it works fine if i take simple array of characters..
I found what is the problem.Here i am writing pointer to strig in file
and after using the structure i am deaalocation memory for it.
so next time when it reads from a file and try to get value at that
pointer,it wont get the actualdata.
so may be i need toserializethedata.

Regards,
Zehra
--
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Hi Jens,
Thanks for the reply.
you are right.
Can you please tell me how would i serialize data in C(can you please
provide example code)?
Also for scanf now i have written

printf("Enter First Name : ");
scanf("%50s",pCustData->pszFirstName);
printf("Enter Last Name : ");
scanf("%50s",pCustData->pszLastName);

i want the name should not acceed 50 char,but here in this case if i
give 52 chars for fisrt name as input it will take 50 for first name
and rest 2 for last name.
it doesnt allow me to enter last name.
So what i sould do to get only 50 chars and discard rest 2 chars?

Thanks & Regards,
Zehra
Jun 27 '08 #5
ze******@gmail.com wrote:

Can you please tell me how would i serialize data in C(can you please
provide example code)?
It's usually better to use existing code than to reinvent the wheel.

<http://tpl.sourceforge.net/>
<http://en.wikipedia.org/wiki/Serialization -- A general overview
Also for scanf now i have written

printf("Enter First Name : ");
To ensure that the above prompt is written to stdout immediately you
should call fflush(stdout) after the printf call.
scanf("%50s",pCustData->pszFirstName);
printf("Enter Last Name : ");
Similarly here too.
scanf("%50s",pCustData->pszLastName);

i want the name should not acceed 50 char,but here in this case if i
give 52 chars for fisrt name as input it will take 50 for first name
and rest 2 for last name.
it doesnt allow me to enter last name.
So what i sould do to get only 50 chars and discard rest 2 chars?
You can use a small function that reads and discards unwanted characters
in the input stream up to the newline character or EOF. Numerous source
examples have been posted here. Do a search of Google Groups' archives
of c.l.c with a search term like "discard input".

However a better approach might be to avoid scanf altogether (since it's
difficult to use in a water-tight manner), and read in lines one by one
with fgets and parse them with sscanf and other functions. A fgets
replacement for the above calls would be like:

if (fgets(input_buffer, input_buffer_length, stdin) == NULL) {
/* A return of NULL means there was a problem. You can deal with
that here.
*/
}

The problem of overlong input still remains. You still need to discard
any input remaining in the stream and check that fgets has read a
complete line. You could treat incomplete reads as either a normal
situation or as an error. That would be program specific.

Jun 27 '08 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
5542
by: rob | last post by:
hey every1, I've got alot of data to write out to file and it's all just 1's and 0's. It's all stored in 2 dimensional arrays of width 32 and varying height. At the moment it's all just...
1
1232
by: Bangalore | last post by:
Hi all, I was trying out the following program, I want to copy the content of struct x variable to file. Here using write of fwrite(used with FILE *fl) I am not able to write integer part to...
29
3530
by: Glen | last post by:
Is it possible to write a structure to a file in c...as in c++...?? is it using fwrite?? thanx glen
2
7793
by: phyzics | last post by:
I am porting an application from C++ to C#, and am having trouble finding a way to quickly and efficiently write structures to a binary file. In C++ this is trivial because all that is necessary is...
2
1739
by: DBC User | last post by:
Hi Sharpies, I have a C program I am converting it into C#. Everything is fine except this process creates a 6K byte binary file. This file initially filled with 6K null and then start...
6
5243
by: arne.muller | last post by:
Hello, I've come across some problems reading strucutres from binary files. Basically I've some strutures typedef struct { int i; double x; int n; double *mz;
6
3511
by: efrenba | last post by:
Hi, I came from delphi world and now I'm doing my first steps in C++. I'm using C++builder because its ide is like delphi although I'm trying to avoid the vcl. I need to insert new features...
5
5132
by: Neil Crighton | last post by:
I'm using the zipfile library to read a zip file in Windows, and it seems to be adding too many newlines to extracted files. I've found that for extracted text-encoded files, removing all instances...
8
1929
by: Bryan.Fodness | last post by:
Hello, I am having trouble writing the code to read a binary string. I would like to extract the values for use in a calculation. Any help would be great. Here is my function that takes in...
0
7109
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7313
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
7372
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
7029
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7481
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
5619
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
5039
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
3179
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
758
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.