C File Registration

3

How to tell 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 in% with%. How do I know if it exists?

    
asked by anonymous 15.05.2014 / 21:50

3 answers

2

As well, "if it exists" ????

If the result of fread() was 1, the registro object was populated with stream information; 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);
}
    
15.05.2014 / 21:56
2

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

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

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

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

caracteres: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa☻
chave: 1633771873
contem: 1633771873
idade: 1633771873
prox: 1633771873
    
15.05.2014 / 22:44
0

For example let's say that 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;
}
    
14.08.2018 / 08:30