无法从文本文件中读取结构 - C

  • 本文关键字:读取 结构 文件 文本 c
  • 更新时间 :
  • 英文 :


我试图使一个函数,将从一个文本文件中读取结构,并将打印它。然而,我的while循环不工作,我不知道为什么:

#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);
}
fclose(dataText);
printf("Donen");
return 0;
}

我的data.txt文件看起来像这样:

Pasta 4.5 2.5
Soup 3.4 1.4
Pie 4.8 3.5

您应该使用fscanf而不是fread函数。这是因为fread期望读取二进制文件,而fscanf期望读取文本文件。

更多关于read和fscanf的详细信息请点击此链接。

最新更新