File handling

C

Chathu

Hello everyone...........
I have a problem on retriving a content of a binary file I wrote into.
My program user structures, dynamic allocation of memory and files. I
take the infomation into a dynamicaly allocated structure and then
write it to a binary file using fwrite() with appending mode. I can
retrive the data I wrote while the program is running. But if I stop
the program and re-execute it I can't read the things I wrote to the
file last time(only some vieard characters appear), but the the data I
wrote this time appeard without any problem.
How can I retrive the data I wrote to the file previousy.
Souce code of the program I wrote is as follows,

#include<stdio.h>
#include<conio.h>
#include<malloc.h>
#include<string.h>
#include<ctype.h>

typedef struct student{
char *name;
int age;
}stu;

void stu_initializer(stu *p,FILE *fp);
void print_stu(stu *p, FILE *fp);

void main()
{
clrscr();
stu *p;
FILE *fp;

//allocate memory for the structure
p=(stu*)malloc(sizeof(stu));
fp=fopen("stu.dat","a+b");

stu_initializer(p,fp);
fclose(fp);

clrscr();
fp=fopen("stu.dat","rb");
print_stu(p,fp);


fclose(fp);
free(p);
}////end main

/////////////////////////////////////////////////////////////////////
//set the information about the parties
void stu_initializer(stu *p,FILE *fp)
{
int a;
char buffer[81];



do{clrscr();
printf("Enter the student name: ");
gets(buffer); fflush(stdin);
//alocate memory for the stu name inside the structure


p[0].name=(char*)malloc((strlen(buffer)+1)*sizeof(char));
strcpy(p[0].name,buffer);//copy the name to the structure

//age of the student
printf("\nEnter the index of the stu? ");
scanf("%d",&p[0].age);
fflush(stdin);
//write to the file
fwrite(p,sizeof(*p),1,fp);
printf("\n\nAny more students?[Y][N] ");
}while(toupper(getch())=='Y');

clrscr();
fflush(stdin);//clear the input buffer


}//end function

/////////////////////////////////////////////////////////////////////
//print the stu list
void print_stu(stu *p, FILE *fp)
{
printf("%s %s \n","Name","Age");
while((fread(p,sizeof(*p),1,fp))==1)
printf("%s %d\n",p[0].name,p[0].age);
}



Please Help me on this problem.......
 
I

infobahn

[Just this once, top-posting seems appropriate.]

April 1st isn't for some weeks.

It's just possible that you aren't trolling. If so, please
observe the following lines of code, all of which have some
problem associated with them. They comprise the vast majority
of the code you posted.
 
C

Chris Williams

You are writing out a structure that has 1) a pointer and 2) an int. To
be certain, your pointer might possibly point to a string, but at the
moment you are only writing out the pointer to your string in
memory--and once the application ends everything that was in memory
will go away and your pointer when read back in the next time you run
the application will just point to some random location in memory with
who knows what data in it.

One thing to note, once you do write out your strings, you will
probably also want to write out their lengths into the file as well.
Either that or you're going to have to read a whole bunch of strings in
and then go searching about for the end of lines or \0s that you wrote
out.

Also, if you open your file with notepad (or whatever), you should be
able to see any text that you have written into it. There will be some
junk characters between the text (which will be the integers) but so
long as there _is_ text you are one step ahead.

-Chris
 
J

Jens.Toerring

Chathu said:
I have a problem on retriving a content of a binary file I wrote into.
My program user structures, dynamic allocation of memory and files. I
take the infomation into a dynamicaly allocated structure and then
write it to a binary file using fwrite() with appending mode. I can
retrive the data I wrote while the program is running. But if I stop
the program and re-execute it I can't read the things I wrote to the
file last time(only some vieard characters appear), but the the data I
wrote this time appeard without any problem.
How can I retrive the data I wrote to the file previousy.
Souce code of the program I wrote is as follows,

Since there are that many errors in this program I mostly restrict
my comments to the first occurence of an error...
#include<stdio.h>
#include<conio.h>
#include<malloc.h>

Both <conio.h> and <malloc.h> aren't standard C header files. Replace
#include<string.h>
#include<ctype.h>
typedef struct student{
char *name;
int age;
}stu;
void stu_initializer(stu *p,FILE *fp);
void print_stu(stu *p, FILE *fp);
void main()

main() is always supposed to return an int. And it has either zero
or two arguments, so make that

int main( void )

(or

int main( int argc, char *argv[ ] )

in case you are interested in the command line arguments).
{
clrscr();

What's that supposed to do? It's not a standard C function.
stu *p;
FILE *fp;

Unless you have a C99 compliant C compiler all variable definitions
mus come before the first executable statement.
//allocate memory for the structure

Please use normal C style comments, i.e. '/*' and '*/', when you
post in newsgroups. The C++ style comments were only introduced
with the new C99 standard and often make it hard to see where a
comment ends when a newsreader wraps long lines.
p=(stu*)malloc(sizeof(stu));

1) Check the return value of malloc().
2) Drop the cast. It's not needed and will keep the compiler from
complaining when you forgot to include the header file where
malloc() is declared in (i.e. said:
fp=fopen("stu.dat","a+b");

Check the return value of fopen().
stu_initializer(p,fp);

There's no declaration of this function (the definition only comes
later), so the compiler can't check if you call it with the correct
arguments,
fclose(fp);
clrscr();
fp=fopen("stu.dat","rb");
print_stu(p,fp);

Again no declaration for the function...
fclose(fp);
free(p);
}////end main

Since main() must return an integer you're missing a return statement
here.
/////////////////////////////////////////////////////////////////////
//set the information about the parties
void stu_initializer(stu *p,FILE *fp)
{
int a;
char buffer[81];
do{clrscr()

printf("Enter the student name: ");

Unless the line ends with a '\n' it usually isn't printed immediately.
You need a 'fflush(stdout);' after this.
gets(buffer); fflush(stdin);

Now, that's really horrible. First of all. Never, ever use gets().
There is no way to keep the user from entering more character
than fit into the buffer gets() puts them in. The function is
broken by design. Use fgets() instead.

Second, you can't fflush() stdin, you can only fflush() output
channels.
//alocate memory for the stu name inside the structure
p[0].name=(char*)malloc((strlen(buffer)+1)*sizeof(char));

sizeof(char) is 1 by definition. And why do you use 'p[0]' here?
Since 'p' isn't an array it would be clearer to use 'p->name'.
strcpy(p[0].name,buffer);//copy the name to the structure
//age of the student
printf("\nEnter the index of the stu? ");
scanf("%d",&p[0].age);

Don't use scanf() when reading user input - if what the user enters
isn't an integer you will get rather starnge results. Use fgets() to
get the whole stuff and then use e.g. sscanf() to get the value,
giving you a chance to check if there was an integer at all.
fflush(stdin);
//write to the file
fwrite(p,sizeof(*p),1,fp);

Now you try to write a structure, containing a pointer to a string.
Once you read back in the file what the pointer points to is rather
likely not the string that was at that address before. You have to
write the string itself into the file, not just a pointer to were
that string was sometime in the past. You might get away with that
here by accident since you read back the structures within the same
program (and since you never deallocate the memory for the strings
once they aren't used anymore), but never if you try to read them
back from a file in a newly started program.

Moreover, you only write out as many bytes as a pointer to such a
structure has because of the '*' in front of 'p'. But if you want
to write out the structure you must fwrite() as many bytes as the
structure is long.
printf("\n\nAny more students?[Y][N] ");
}while(toupper(getch())=='Y');

getch() isn't standard C function, so I can't see if this here is
correct...
clrscr();
fflush(stdin);//clear the input buffer

No, you clear the input buffer by reading until nothing is in
there anymore.
}//end function
/////////////////////////////////////////////////////////////////////
//print the stu list
void print_stu(stu *p, FILE *fp)
{
printf("%s %s \n","Name","Age");
while((fread(p,sizeof(*p),1,fp))==1)

This won't work for the multiple reasons given above.
printf("%s %d\n",p[0].name,p[0].age);
}

As a rule writing out structures in binary form is a bad idea. Even
if you get it right it will only work in case you read back the file
on a machine with the same archtitecture and may require to have the
programs for writing and reading where compiled with the same com-
piler.
Regards, Jens
 
P

parser

hey man what u r trying to do is just write the pointers to a file. u
never wrote the actual data to the file. see

struct stu *p;
p=(stu*)malloc(sizeof(stu));
just allocates storage for structure of type stu and then

p[0].name=(char*)malloc((strlen(buffer)+1)*sizeof(char));
just allocates the memory which in no way stored as a part of struct
stu. rather u are accessing it as stu->name

the statement
fwrite(p,sizeof(*p),1,fp);
writes some data stored in p{name(a pointer) and age}. But the actual
string pointed to by p->name still is unwritten to the file.

the result is that u are writing only the address of the string u
enterd and an integer
nothing more nor less. if u still have problems do write in to me
 
C

CBFalconer

parser said:
hey man what u r trying to do is just write the pointers to a file. u
never wrote the actual data to the file. see

The combination of no quotes, disgusting abbreviations, and silly
"hey man" immediately confirms my idea that this is not worth
reading.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
474,263
Messages
2,571,064
Members
48,769
Latest member
Clifft

Latest Threads

Top