I have a data file and I want to read it into a struct.
This is the contents of the data file
Japan 46.2 16 12.7
Spain 42.8 18.5 39.3
Italy 53.25 19.8 32.8
France 54.5 21.1 31.4
Turkey 52.5 15.6 19.1
This is my code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
struct covid
{
char location[100];
double does_given;
double full_vaccinated;
double of_population_fully_vaccinated;
};
FILE *infile;
infile=fopen("test.txt","r");
if (infile == NULL)
{
fprintf(stderr, "\nError opening file\n");
exit (1);
}
struct covid stats;
while (fread(&stats,sizeof(struct covid),1,infile)){
printf("name =%s, give =%f, full=%f, pop=%f\n",stats.location, stats.does_given, stats.full_vaccinated, stats.of_population_fully_vaccinated);
};
fclose(infile);
return 0;
}
However, when I run this code, I get no output. Why doesn't it work?
fgetsandsscanfcould be useful.foo.txt,foo.datorfoo.bar, you must still read it line by line and parse each line.