Registration with C file

How do I know if there is a record (struct) saved in some position in a file in C ?

For struct:

typedef struct Registro
{
     int chave;
     char caracteres[20];
     int idade;
     int prox;
     bool contem;
} Registro;

For example:

fseek(fl,0*sizeof(Registro),SEEK_SET);
fread(&registro,sizeof(Registro),1,fl);

Position 0 information was loaded into registro. How to know if it exists ?

 3
Author: Lucas Lima, 2014-05-15

3 answers

What do you mean, "if he exists"????

If the result of fread() was 1, the object registro was populated with information from stream ; if the result was 0 there was an error that you can determine by errno

if (fread(&registro, sizeof (Registro), 1, fl) == 0) {
    perror("Registro");
    // exit(EXIT_FAILURE);
}
 2
Author: pmg, 2014-05-15 19:56:50

In addition to the check that @pmg presented, I would recommend doing a check of the data read, to make sure that it is what you expect and to make sure that Registro exists.

For example, if you create a file arquivo.dat filled like this:

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

And then read it as a Registro, your program will work perfectly. The file exists, it has enough content to fill the sizeof(Registro) but the content is not of a Registro (this would be a false positive in your programme):

caracteres: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa☻
chave: 1633771873
contem: 1633771873
idade: 1633771873
prox: 1633771873
 2
Author: Lucas Lima, 2014-05-15 20:44:26

For example let's say the file was created like this:

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>

typedef struct Registro
{
 int chave;
 char caracteres[20];
 int idade;
 int prox;
 bool contem;
} Registro;

int main(){
Registro registro = {0,"",0,0,false};

FILE *fPtr;
if((fPtr = fopen("arquivo.dat","wb")) == NULL){
    printf("Erro na abertura do arquivo\n");
}
else{
     /* Inicializa dez campos "vazios" no arquivo,sem dados de usuario */
    for(i = 0 ; i < 10 ; i++){
         fwrite(&registro,sizeof(Registro),1,fPtr);
    }
    fclose(fPtr);
 }

return 0;
}

We can check for "empty" fields by doing the following:

int main(){

Registro registro = {0,"",0,0,false};

FILE *fPtr;
if((fPtr = fopen("arquivo.dat","rb")) == NULL){
    printf("Erro na abertura do arquivo\n");
}
else{
    fseek(fPtr,0*sizeof(Registro),SEEK_SET);
    fread(&registro,sizeof(Registro),1,fPtr);

    if(registro.chave == 0 && strcmp(registro.caracteres,"") == 0){
        printf("Esse campo esta vazio!\n");
    }
    else{
        printf("Esse campo contem dados!\n");
    }
    fclose(fPtr);

 }
return 0;
}
 0
Author: Igor PTZ, 2018-08-14 06:36:57