...

View Full Version : File Handling problem in c



ashishchaudhary
10-13-2011, 05:55 PM
Hello everyone,

today my problem is in file handling in c, here is my code



#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

struct rec {
char name[50];
char age[5];
};

void enterRecord(FILE *, struct rec *);
void displayRecord(FILE *, struct rec *);
void menu(void);
int main(void)
{
FILE *p;
struct rec *r;
int opt=0;
clrscr();

while(1)
{
menu();
opt = 0;
scanf("%d", &opt);
switch(opt)
{
case 1:
p = fopen("record.txt", "a+b");
if(p==NULL)
{
printf("Error in opening file.");
getch();
break;
}
enterRecord(p,r);

break;
case 2:
p = fopen("record.txt", "r+b");
if(p==NULL)
{
printf("Error in opening file.");
getch();
break;
}
displayRecord(p,r);

break;
case 3:
exit(1);
}
getch();
clrscr();
}

getch();
return 0;


}

void menu(void)
{
printf("1. Enter record.\n");
printf("2. Display record.\n");
printf("3. Exit.\n");
printf("Enter your choice : ");
}
void enterRecord(FILE *p, struct rec *r)
{
fflush(stdin);
printf("Enter name : ");
gets(r->name);
printf("\n");
printf("Enter age : ");
gets(r->age);
fseek(p, 0L, SEEK_END);
fwrite(r,sizeof(struct rec),1,p);
printf("\nRecord entered.\n");

}

void displayRecord(FILE *p, struct rec *r)
{
fseek(p, 0L, SEEK_SET);
while(1 == (fread(r,sizeof(struct rec),1,p)))
{
printf("Name : ");
puts(r->name);
printf("\n");
printf("Age : ");
puts(r->age);
}


}


this code is working properly, but the problem is that when i enter a record at run time that's work properly but when i choose option 2 to see that record i don't get that record but when i recompile my program and choose option 2 then i get that record,
So the problem is that i don't get the newly entered record at run time.untill i don't recompile my program, only i get the previous entered record.
What can be the problem i don't have any idea,
Please if any body know the reason please tell me in detail.

Thank you.

bobleny
10-14-2011, 07:13 AM
The reason you are not able to write to the file and then read from the file without exiting you program is because you are not closing the file. You open it to write, but since you never closed it, it never reopens it for reading.

After you return from your enter/displayRecord() function, simply add the following line:

fclose(p);

On a side note, you are declaring a pointer to a structure, but you are not assigning it a value.

struct rec *r;

I'm really quite surprised it isn't segfaulting.
It would be better to declare a structure called rec:

struct rec r;

Then point to it in your enter/displayRecord() function like this:

enterRecord(p, &r);



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum