#include <stdio.h>
#define LAST_MAX 15
#define FIRST_MAX 15
typedef struct
{
char last[LAST_MAX+1];
char first[FIRST_MAX+1];
int empno;
} Employee;
toString(Employee* e, FILE* out)
{
fprintf(out, "{%s, %s, %d}", e->last, e->first, e->empno);
}
int main()
{
Employee e1 = {"doe", "john", 1};
Employee e2 = {"dough", "jane", 2};
FILE* f;
/* Build 2 records: */
toString(&e1, stdout);
putchar('\n');
toString(&e2, stdout);
putchar('\n');
/* Create file: */
if ((f = fopen("employees.dat","w+b")) == NULL)
return -1;
if (fwrite(&e1,sizeof(Employee),1,f) != 1)
return -1;
if (fwrite(&e2,sizeof(Employee),1,f) != 1)
return -1;
/* Swap on re-reading: */
fseek(f, sizeof(Employee), SEEK_SET);
fread(&e1, sizeof(Employee), 1, f);
rewind(f);
fread(&e2, sizeof(Employee), 1, f);
toString(&e1, stdout);
putchar('\n');
toString(&e2, stdout);
putchar('\n');
fclose(f);
return 0;
}
End of Listing