Home > front end >  Can't read a structure from text file - C
Can't read a structure from text file - C

Time:12-07

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

CodePudding user response:

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.

  •  Tags:  
  • c
  • Related