[ad_1]
I have this file for example:
Aluno;p1;p2
Joao;5.5;2.1
Maria;8.0;7.5
Jose;9.5;9.5
and I need to read this file, and store it in a struct, like this:
struct aluno
{
char nome[10];
char p1;
char p2;
};
My code: (I don’t know how to proceed anymore)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct aluno
{
char nome[10];
char p1;
char p2;
}dict;
int main()
{
FILE * fp;
dict aluno[9];
char nomeArq[10];
printf("Enter the file name: ");
scanf("%10[^\n]", nomeArq);
if((fp = fopen(nomeArq, "r")) == NULL)
{
printf("Error %s\n", nomeArq);
return 1;
}
char buffer[1024];
int field=0;
int i=0;
while(fgets(buffer, 1024, fp) != NULL)
{
char *token = strtok(buffer, ";");
while(token)
{
if(campoCount == 0)
{
strcpy(aluno[i].nome, token);
}
if(campoCount == 1)
{
strcpy(aluno[i].p1, token);
}
if(campoCount == 2)
{
strcpy(aluno[i].p2, token);
}
token = strtok(NULL, ";");
campoCount++;
}
i++;
}
fclose(fp);
printAlunos(aluno);
return 0;
}
void printAlunos(dict aluno[])
{
int i;
for(i=0;i<3;i++)
{
printf("%s\n", aluno[i].nome);
printf("%s %s\n", aluno[i].p1, aluno[i].p2);
}
}
PS: The header must be included
Aluno;p1;p2
I did a lot of research in the last few days, and all the tutorials I found were reading CSV files that didn’t have columns, and for that reason, didn’t work in my code. I don’t know what else to do. This is an excel spreadsheet, for the record
[ad_2]