0
Good morning,
I have the following structures:
typedef struct celCidade *apontadorCidade;
typedef struct celEstado *apontadorEstado;
typedef struct{
char nome[100];
int populacao;
int beneficiarios;
int qtdCidades;
float idh;
apontadorEstado proxEstado;
apontadorCidade Arv;
}celEstado;
typedef struct{
char nomeCidade[100];
char nomeEstado[100];
int populacao;
int beneficiarios;
float idhm;
apontadorCidade esq;
apontadorCidade dir;
}celCidade;
Each field of this structure has its data contained in a file. csv, where each city should be associated with its due state, then the screening should be done while reading the data with its due if’s and Else’s and because it is a file with a considerable amount of data, I would like to read through a while()
, because I find it more practical, where the stopping condition would be when there is no more data to be read.
So far I’m at square one.
void carregaArquivo(FILE *arquivo){
arquivo = fopen("data.csv", "r");
if(arquivo != NULL){
printf("Arquivo lido com sucesso!\n");
}else{
printf("Erro ao carregar o arquivo!\n");
}
}
Here’s the problem: I have no idea how to do this reading, I’ve read about fscanf()
, fgets()
and other ways I can use to read this data, but I would like to know:
- What is the best function to read lines of a CSV file
- How to identify the order of fields in the program
- What would be the stopping condition of the
while()
?
Thank you in advance!
You can read a file. txt?
– Andre Lacomski
No, it’s the same thing in csv?
– H.Lima
Same thing, but it has several ways to read. I recommend searching for fscanf or fread functions to read the file. The while stop condition can check if you found the end of the while file (fscanf()!=EOF) it continues reading. You have to see what you need to do, to get an idea of how it looks best to perform this reading
– Andre Lacomski
"How to identify the order of the fields in the program": you need to know what you are reading, usually this means knowing which fields and in what order they will be in the file being read. " What would be the stop condition of while()": test by EOF at each reading.
– anonimo
Thanks for the tips, I will seek to know more about EOF and updated the question anything
– H.Lima
best function to read per line is "fgets"; then has the analysis of the fields of a csv line; this task may not be trivial, depending on the accepted formats (for example, may have fields delimited by quotation marks ?" etc); if for professional use (and not as a college exercise) probably the most suitable is to look for some ready lib for that task (google "csv c library")
– zentrunix
thanks for the zentrunix tip!
– H.Lima