Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
242 views
Welcome To Ask or Share your Answers For Others

1 Answer

You're just writing one Persons structure to the file. You shouldn't use persons->counter as the number of items that you're writing or reading, as the array is entirely contained in the structure.

You also shouldn't open the file in append mode. Since you're writing the entire Persons structure, not a single person, you should open it in write mode and overwrite the whole file.

The first argument to fwrite() and fread() should be persons, not &persons, since you want to fill in the structure that it points to, not overwrite the pointer.

To make sure you don't write outside the array, you should check that persons->counter hasn't exceeded the size of the array.

int writeStruct(Persons *persons,char *file){
    FILE *outfile; 

    if (persons->counter >= MAX_PERSON) {
        puts("File is full
");
        return persons->counter;
    }

    outfile = fopen (file, "wb"); 
    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), 1, outfile); 
      
    if(fwrite == 1){  
        puts("Success 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), 1, infile);
   
    // close file 
    fclose(infile);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...