yasaaMoin yasaaMoin - 3 months ago 13
C Question

C File program doesnt execute fopen

after saving the program in turbo c++,the place where its saved doesnt show the file's individual components,and its executing twice.Its for a college project.The problem seems to be for the portion of code written for opening and in the for loop

#include<stdio.h>
typedef struct
{
int select;
char lastname[25];
char firstname[25];
char address[25];
char phonenumber[25];
} addressbook;

#define ARRAYLEN 2

addressbook a[ARRAYLEN];
FILE *fp;

int main()
{
int i;

fp = fopen("addressbook.dat","a+");

for( i=0; i<ARRAYLEN ; i++)
{
printf("enter details\n");
printf("enter lastname:\n");
scanf("%s", a[i].lastname);
printf("enter firstname:\n");
scanf("%s", a[i].firstname);
printf("enter address:\n");
scanf("%s", a[i].address);
printf("enter phone number:\n");
scanf("%s", a[i].phonenumber);
fwrite(&a[i], sizeof(a), 1, fp); /* notice, array indexed */
}
fclose(fp);

fopen("addressbook.dat", "r");
for(i=0; i<ARRAYLEN; i++)
{
fread(&a[i], sizeof(a), 1, fp );
printf("lastname:%s\n", a[i].lastname);
printf("firstname:%s\n", a[i].firstname);
printf("address:%s\n", a[i].address);
printf("phonenumber:%s\n", a[i].phonenumber);
}
fclose(fp);

return 0;
}

Answer

The problem is with the use of 'fp' - File Pointer.

After the first use of fopen, you are closing it, and then use fopen again.

But this time, you are not place it return value into fp. So your following actiond (like fread) creates undetermenated results.

Please replace -

fopen("addressbook.dat", "r");

with

fp = fopen("addressbook.dat", "r");

Other problems in your code -

  1. Always check for return value

  2. You need to verify that values received from user, do not exceed allowed space given to variables

  3. It goes without saying, but you are using fclose(fp) twice on your corrent solution