Search code examples
cfgets

Unexpected output reading from a file


I've got a text file that I want to read. The file has the following content:

Asdsf adsfsd
54
asdfa adwfasd
12
asdf adf 
545
asdf asdfasfd
3243
adfasf asdfasdf
324324
asfda asdfasdf
3124
adfa asdfas
432
asdf ad

and my code:

#include <stdlib.h>
#include <string.h>
#include <stdio.h>


struct Element {
    int edad;
    char name[50];
};

int main() {
    struct Element aux;
    FILE* fitxer;
    fopen_s(&fitxer, "Text.txt", "r");
    if (fitxer != NULL) {
        while (!feof(fitxer)) {
            fgets(aux.name, 50, fitxer);
            aux.name[strlen(aux.name) - 1] = '\0';
            int ret = fscanf_s(fitxer, "%i", &aux.edad);
            char endl;
            fscanf_s(fitxer, "%c", &endl);
            printf("%d %s \n", aux.edad, aux.name);
        }
        fclose(fitxer);
    }
    else {
        printf("Error: File not found.");
    }    
}

I had problems before because I didn't know that f_scanf doesn't take the endline character. Now the problem is that there are some strings in the file that are being chopped. Output:

54 Asdsf adsfsd
12 asdfa adwfasd
545 asdf adf
3243 asdf asdfasfd
324324 adfasf asdfasdf
3124 asfda asdfasdf
432 adfa asdfas
432 asdf a

For instance, in this example the last letter is being chopped. I suspect it has something to do with the conversion to string, adding the '\0' character, but I'm unable to find the error.

Also I would like to ask if there is a way to do it more elegant.


Solution

  • At least 3 problems:

    Wrong test for end-of-file, avoid magic numbers

    ref

    //while (!feof(fitxer)) {
    //    fgets(aux.name, 50, fitxer);
    while (fgets(aux.name, sizeof aux.name, fitxer)) {
    

    fscanf_s(fitxer, "%c", &endl); is missing an augment.

    Research fscanf_s() if interested, or better yet, just use fgets() for input.

    Wrong code to lop off potential trialing '\n'

    Alternatives: 1 2

    // aux.name[strlen(aux.name) - 1] = '\0';
    aux.name[strcspn(aux.name, "\n")] = '\0';