473,573 Members | 2,786 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.da t","ab+");
return fp;
pCustdata = malloc(sizeof(C UST_DATA));

pCustData->szFirstName = malloc(sizeof(p CustData-
>szFirstName) );
printf("Enter CAFID : ");
scanf("%d",&pCu stData->nCAFID);

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

fwrite(pCustDat a,sizeof(CUST_D ATA),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 3802
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.da t","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(C UST_DATA));
What if it fails?
>
pCustData->szFirstName = malloc(sizeof(p CustData-
>>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",&pCu stData->nCAFID);

printf("Enter First Name : ");
scanf("%s",pCus tData->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(pCustDat a,sizeof(CUST_D ATA),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.da t","ab+");
return fp;
pCustdata = malloc(sizeof(C UST_DATA));
pCustData->szFirstName = malloc(sizeof(p CustData->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",&pCu stData->nCAFID);
printf("Enter First Name : ");
scanf("%s",pCus tData->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(pCustDat a,sizeof(CUST_D ATA),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.i nvalidwrote:

Thaks a lot for the reply..
zehra...@gmail. com said:
Hi,
I had written application for storing employee data inbinaryfileand
reading those data frombinaryfilea nd 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.da t","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(C UST_DATA));

What if it fails?
pCustData->szFirstName = malloc(sizeof(p CustData-
>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",&pCu stData->nCAFID);
printf("Enter First Name : ");
scanf("%s",pCus tData->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(pCustDat a,sizeof(CUST_D ATA),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.i nvalidwrote:

Thaks a lot for the reply..
zehra...@gmail. com said:
Hi,
I had written application for storing employeedatainb inaryfileand
reading thosedatafrombi naryfileand 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.da t","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(C UST_DATA));
What if it fails?
pCustData->szFirstName = malloc(sizeof(p CustData-
>>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",&pCu stData->nCAFID);
printf("Enter First Name : ");
scanf("%s",pCus tData->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(pCustDat a,sizeof(CUST_D ATA),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 toserializethed ata.

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",pC ustData->pszFirstName );
printf("Enter Last Name : ");
scanf("%50s",pC ustData->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.or g/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",pC ustData->pszFirstName );
printf("Enter Last Name : ");
Similarly here too.
scanf("%50s",pC ustData->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_bu ffer, input_buffer_le ngth, 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
5545
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 integer arrays and the individual 1's and 0's are being written out as integers.
1
1237
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 the file. Is there any to copy all contents of structure to file? struct x{ char a;
29
3549
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
7797
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 to pack the structure to 1 byte boundries, and then just write out the structure directly to the File IO function pragma pack (1 typedef struct...
2
1752
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 populating only the fields with value in specified locations(3 seperate structures). The way the C does is by creating a structures, which will be filled...
6
5248
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
3515
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 to an old program that I wrote in delphi and it's a good opportunity to start with c++.
5
5141
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 of '\r' in the extracted file seems to fix the problem, but I can't find an easy solution for binary files. The code I'm using is something...
8
1933
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 a string. def parseSequence(data, start):
0
7755
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7679
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
6385
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5571
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5281
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3722
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3722
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2183
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1284
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.