C I/O Question

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.

Any sujections?

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

#define FNAME "c:\\Users\\pronesti\\My Documents\\emp.dat"

struct employee
{
char name[31];
char address[101];
int age;
float salary;
};

typedef struct employee emp;

static void read_emp(emp *e)
{
printf("Please enter the name: ");
fflush(stdin);
scanf("%[^\n]", &e->name);

printf("Please enter the address (on one line): ");
fflush(stdin);
scanf("%[^\n]", &e->address);

printf("Please enter the age: ");
fflush(stdin);
scanf("%d", &e->age);

printf("Please enter the salary: ");
fflush(stdin);
scanf("%f", &e->salary);
}

static void print_emp(emp *e)
{
printf("name is %s\n", e->name);
printf("address is %s\n", e->address);
printf("age is %d\n", e->age);
printf("salary is $%.2f\n", e->salary);
}

static void pause()
{
printf("\nProgram ended, press ENTER: ");
fflush(stdin);
getchar();
}

static void file_write(emp *e, FILE **fw_ptr)
{
int fw_i = 0;

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;

}
Does the file have anything in it when you check it by hand?
Yes, this is what shows up when I open it in windows.

 þ(

When I run my code it says "0 records were written and read"
Last edited on
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.
Thank you, I just modified it so it doesn't pass in &e and it worked. I was thinking I had somthing wrong with the file ptr.
Topic archived. No new replies allowed.