My program scans names and birth years and stores them in an array of structures. Scanning from keyboard and printing in screen works fine, but I'm not sure whether printing in my binary file is correct because my program runs without errors and I can't check if the data has been printed correctly in the binary file. My question is about whether the syntax of my "fwrite" functions is correct.
#include <stdio.h>
#define MAXNAME 50 //size of name
#define MAXPERSONS 2 //Max num of persons
typedef struct{
char name[MAXNAME];
int year;
}person_t;
int read_person(person_t[], int);//scans the person
int write_person(const person_t[], int, FILE*);//prints the persons in the screen and the bfile
int main()
{
FILE *pfile;
person_t v[3];
int iscan=0,iprint;
if((pfile=fopen("persons.bin","wb"))==NULL) printf("couldnt open<vehicles.txt>\n");
else{
while(iscan<MAXPERSONS){
read_person(&v[iscan],iscan+1);
iscan++;
}
for(iprint=0;iprint<iscan;iprint++)
write_person(&v[iprint],iprint+1,pfile);
}
fclose(pfile);
printf("\n\n");
return 0;
}
int read_person(person_t v[],int i)
{
printf("Person %d",i);
printf("\n\tName: ");
fflush(stdin);
gets(v->name);
printf("\n\tYear: ");
scanf("%d",&v->year);
}
int write_person(const person_t v[],int j, FILE *pfile)
{
//print in screen
printf("\nPerson %d",j);
printf("\n\tName: %s\n",v->name);
printf("\n\tYear: %d\n",v->year);
//print in the binary file
fwrite(v->name,sizeof(char),1,pfile);
fwrite(&v->year,sizeof(int),1,pfile);
}
This program reads from the bin file
#include<stdio.h>
#define MAXNAME 50 //size of name
#define MAXPERSONS 2 //Max num of persons
typedef struct{
char name[MAXNAME];
int year;
}person_t;
int read_person(person_t[], int, FILE*);
int write_person(const person_t[], int);
int main(){
FILE *pfile;
person_t v[3];
int iscan=0,iprint;
if((pfile=fopen("persons.bin","rb"))==NULL) printf("couldnt open<vehicles.txt>\n");
else{
while(iscan<MAXPERSONS){
read_person(&v[iscan],iscan+1,pfile);
iscan++;
}
for(iprint=0;iprint<iscan;iprint++)
write_person(&v[iprint],iprint+1);
}
fclose(pfile);
printf("\n\n");
return 0;
}
int read_person(person_t v[],int i, FILE *pfile){
//read from the binary file
fread(v->name, sizeof(v->name),1,pfile);
fread(&v->year,sizeof(v->year),1,pfile);
}
int write_person(const person_t v[],int j){
//print in screen
printf("\nPerson %d",j);
printf("\n\tName: %s\n",v->name);
printf("\n\tYear: %d\n",v->year);
}