简体   繁体   English

fread() function 打印一行额外的随机字符

[英]fread() function prints an extra line of random characters

I am trying to read data from a file and save it to a struct and print it to a screen.我正在尝试从文件中读取数据并将其保存到结构中并将其打印到屏幕上。 Everything works but it print and extra line of characters.一切正常,但它打印和额外的字符行。 I tried using malloc but I don't think I am using it correctly.我尝试使用 malloc,但我认为我没有正确使用它。 Here is the code.这是代码。

void SearchItem(struct grocery NewList) {
    struct grocery NList;
    char sitem[50];
    
    NList.list = fopen("grocerylist.txt", "r");

    if (NList.list == NULL) {
        printf("File could not be opened. \n");
    } else {
        fseek(NList.list, 0, SEEK_END);
        int sz = ftell(NList.list);
        rewind(NList.list);
        char *Data = (char *)malloc(sz + 1);
  
        for (int i = 0; i < strlen(Data); i++) {
            fread(&NList, sizeof(struct grocery), 1, NList.list);
         
            if (NList.item_name != NULL) {
                printf("\n %s %.2f %d", NList.item_name,
                       NList.unit_price, NList.quantity);
            } else {
                 printf("Item unavailable.\n");
            }
        }
    }
    fclose(NList.list);
}

Here is the output from file这是文件中的 output

在此处输入图像描述

and here is the contents of the file这是文件的内容

在此处输入图像描述

How do I Fix This我该如何解决

Thanks to all your comments they led me to a solution.感谢您的所有评论,他们让我找到了解决方案。

Here is what fixed my code,这是修复我的代码的原因,

while(.feof(NList.list))

I Changed the for loop back to a while loop and我将 for 循环改回 while 循环并

fscanf(NList.list, "%[^ ] %f %d\n", NList.item_name, &NList.unit_price, &NList.quantity);

Instead of fread() I used the fscanf() and instead if using %s for the string, I used %[^ ] and the \n allowed it to read the next line.我使用fscanf()而不是fread() ) ,如果使用%s作为字符串,我使用%[^ ]并且\n允许它读取下一行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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