简体   繁体   中英

Can't read a structure from text file - C

I'm trying to make a function that would read structures from a TEXT file and would print it. However, my while loop doesn't work somehow and I don't know why:

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

 struct data {
     char foodName[FILENAME_MAX];
     int rating;
     double price;
 };

 FILE* openFile(char antraste[], char rezimas); <--- this function works ant it just opens a text file, so don't look into this


 int main() {

     FILE* dataText = openFile("Input data file: ", 'r');

     struct data food;

     while(fread(&food, sizeof(struct data), 1, dataText)) <--- it doesn't go inside the cycle
      {
         printf ("name = %s rating = %d price = %d\n", food.foodName, food.rating, food.price);
      }

     fclose(dataText);

     printf("Done\n");

     return 0;
 }

My data.txt file looks like this:

Pasta 4.5 2.5
Soup 3.4 1.4
Pie 4.8 3.5

You should use fscanf and not the fread function. This because the fread expect to read a binary file, while the fscanf read the text file.

More detailed info on fread and fscanf at this link.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM