-2

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. 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

enter image description here

and here is the contents of the file

enter image description here

How do I Fix This

chqrlie
  • 131,814
  • 10
  • 121
  • 189
Strawberry Raen
  • 23
  • 1
  • 1
  • 5
  • 2
    Look at the value returned by `fread()` to see whether it was successful or not. You ignore what it returns — you've no idea what's valid and what isn't valid. – Jonathan Leffler Apr 06 '22 at 00:48
  • The file you've shown is not formatted properly for reading as binary. `for(int i = 0; i – Retired Ninja Apr 06 '22 at 00:50
  • 1
    Side note: Your program would be easier to read (both for yourself and other people) if you used consistent indentation. – Andreas Wenzel Apr 06 '22 at 01:01
  • Enable all warnings to see why `Data[sz] = "\0";` is bad. – chux - Reinstate Monica Apr 06 '22 at 04:18
  • ... and post a [mre] instead of dumping all the code you are working on. – Allan Wind Apr 06 '22 at 08:44
  • Okay so Some of your comments were kinda harsh, as I am a beginner coder and I am learning. That being said, I will try all of your suggestions. and let you all know what works – Strawberry Raen Apr 07 '22 at 07:12
  • @RetiredNinja Ninja Can you suggest a better way to get this done? – Strawberry Raen Apr 07 '22 at 07:15
  • @chux-ReinstateMonica Its Says [Error] assignment to 'char' from 'char *' makes integer from pointer without a cast [-Werror=int-conversion] When I googled the error its say that happens when I assign a string to a pointer – Strawberry Raen Apr 07 '22 at 07:29
  • @RetiredNinja I Used ` fread(&NList, sizeof(struct grocery), 2, NList.list);` Because it chopping the last line and printing garbage. when I used `fscanf()` all my values were printing in the string variable only, the float and integers variables just showed 0. fread() prints them in their variables, except the last line. – Strawberry Raen Apr 07 '22 at 07:34
  • @AllanWind first time I heard of it, Thank you for letting me know. – Strawberry Raen Apr 07 '22 at 07:36
  • @RetiredNinja I made the changes, please see my output, this was original issue. – Strawberry Raen Apr 07 '22 at 07:52

1 Answers1

0

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

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.

chqrlie
  • 131,814
  • 10
  • 121
  • 189
Strawberry Raen
  • 23
  • 1
  • 1
  • 5
  • 1
    For safety, instead of `%[^ ]`, you should use `%49[^ ]` if `Nlist.item_name` has a length of `50`. Furthermore, you should check that the return value of `fscanf()` is `3`, the number of requested conversions. – chqrlie Apr 07 '22 at 08:37
  • 1
    To stop the loop, do not use `while(!feof(NList.list))`, just test the return value of `fscanf()`: `while (fscanf(...) == 3)` – chqrlie Apr 07 '22 at 08:38
  • 1
    Read [Why is `while ( !feof(file))` always wrong?](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) – chqrlie Apr 07 '22 at 08:40