Can't read a structure from text file – C

Can't read a structure from text file – C

Problem Description:

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 = %dn", food.foodName, food.rating, food.price);



     return 0;

My data.txt file looks like this:

Pasta 4.5 2.5
Soup 3.4 1.4
Pie 4.8 3.5

Solution – 1

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.

Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.