I have this code, and want that the program reads/loads the data that is on the file and them printed them, but this didn′t work.
I can′t write on the file, but can′t read it.
I want that when the program initialize, he already have loaded the info that is in the the binary file, so the user can use it, for example for searching people.
#include <stdio.h>
#include <stdlib.h>
#define MAX_PERSON 3
#define FILENAME "person.bin"
typedef struct {
int id;
char fname[20],lname[20];
}person;
typedef struct {
int counter;
person persons[MAX_PERSON];
}Persons;
int writeStruct(Persons *persons,char *file){
FILE *outfile;
outfile = fopen (file, "ab+");
if (outfile == NULL){
exit(EXIT_FAILURE);
}
printf("
Insira a informa??es da pessoa
");
printf("Código: ");
scanf("%d", &persons->persons[persons->counter].id);
printf("Primeiro Nome: ");
scanf("%s", persons->persons[persons->counter].fname);
printf("último Nome: ");
scanf("%s", persons->persons[persons->counter].lname);
fwrite (&persons, sizeof(Persons), persons->counter, outfile);
if(fwrite != 0){
puts("Sucess on writing on file");
}else{
puts("Error on writing on file");}
fclose (outfile);
return persons->counter++;
}
void loadStruct(Persons *persons,char *file){
FILE *infile;
// Open person.bin for reading
infile = fopen(file, "rb+");
if (infile == NULL) {
fprintf(stderr, "
Error opening file
");
exit(1);
}
// read file contents till end of file
fread(&persons, sizeof (Persons), persons->counter, infile);
// close file
fclose(infile);
}
void listPersons(Persons persons){
int i;
puts("Lista de pessoas");
puts("-----------------");
for(i=0;i < persons.counter; i++) {
printPerson(persons.persons[i]);
}
puts("-----------------");
}
void searchPeople(Persons persons) {
int number;
printf("Indique o código da pessoa que pretende procurar: ");
scanf("%d",&number);
number = searchPerson(persons,number);
if (number != -1) {
printPerson(persons.persons[number]);
} else {
puts(ERROR_PERSON_NOT_EXISTS);
}
}
int searchPerson(Persons persons,int number) {
int i;
for (i = 0; i < persons.counter; i++) {
if (persons.persons[i].id == number) {
return i;
}
}
return -1;
}
void printPerson(person person){
printf("%d - %s %s
", person.id,person.fname, person.lname);
}
int main ()
{
int op;
Persons persons ={.counter = 0};
loadStruct(&persons,FILENAME);
do{
puts("PESSOAS - BASE DE DADOS");
puts("-----------------");
puts("2 - Inserir pessoa");
puts("3 - Listar pessoas");
puts("4 - Procurar pessoa");
puts("0 - Sair");
puts("-----------------");
printf("No Pessoas: %d/%d
", persons.counter, MAX_PERSON);
printf("Op??o:");
scanf("%d",&op);
printf("
");
switch (op) {
case 0:
exit(0);
break;
case 2:
writeStruct(&persons,FILENAME);
break;
case 3:
listPersons(persons);
break;
case 4:
searchPeople(persons);
break;
default:
puts("Op??o inválida!");
break;
}
}while(op!=0);
}
question from:
https://stackoverflow.com/questions/65837295/c-reading-values-from-a-binary-file-and-then-print-them 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…