I wrote this code to open a file to write records to it, then pass it in to a function for writting, then when I return from the function and go to read it has nothing in it. I tried passing the address into a double pointer and that didn't work either.
if (fwrite(&e, sizeof e, 1, *fw_ptr) < 0)
{
perror("Couldn't write to the file" FNAME);
exit(1);
}
}
main()
{
FILE *fptr;
emp e;
int count;
int i;
atexit(pause);
fptr = fopen(FNAME, "wb");
if(fptr == NULL)
{
perror("Couldn't opnen(w) the file" FNAME);
exit(1);
}
printf("How many employees do you want to enter: ");
scanf("%d", &count);
for (i = 0; i < count; i++)
{
printf("Pleae enter details for employee %d:\n", i+1);
read_emp(&e);
file_write(&e, &fptr);
}
fclose(fptr);
fptr = fopen(FNAME, "rb");
if (fptr == NULL)
{
perror("Couldn't opnen(w) the file" FNAME);
exit(1);
}
for (i = 0; fread(&e, sizeof e, 1, fptr) == 1; i++)
{
puts("========================");
printf("Details of employee %d are:\n", i+1);
print_emp(&e);
}
printf("\n%d records were written and read\n", i);
fclose(fptr);
return 0;
Why do you write emp e when what you really need is emp e[count]? In fact, since the number of employees cannot be determined at compile time, you may want to use a dynamic array:
1 2 3
printf("How many employees do you want to enter: ");
scanf("%d", &count);
emp *e = malloc(count * sizeof(emp));
Read the documentation of fwrite and fread and learn how they're used.