0

I am trying to read from a text file and this is my file reader:

int readFile(char strArray[MAX][MAX]) {
    FILE *infile;
    infile = fopen("input.txt", "r");
    int row = 0;
    if(infile == NULL)
        exit(0);
    while(feof(infile) == 0) {
        fgets(strArray[row], 100, infile);
        row++;
    }
    fclose(infile);
    return row;
}

and the content of the "input.txt" file I was trying to read:

hello
goodbye
**an empty line***

The problem occurred when I left the last line of the text file as empty, my program prints out undefined symbols. I have fixed this issue by removing the last empty line in the text file.

But I am wondering if there is a way to leave the empty line at the bottom of the text file ?

I have tried the solution from this stackoverflow post but it didn't work and it also froze my complier.

I know that I should not try using feof() from this stackoverflow post so should I use fgets() to check the characters from my loop and I would love to know some more other alternative ways?

CosmosLee
  • 57
  • 3
  • 7
  • 1
    Try changing your reading loop to this: https://prnt.sc/1306ih7 (if the links doesn't open, try again later.. sometimes Lightshot goes down). It removes `'\n'` from the end of the lines while parsing the text-file . – Harry K. May 16 '21 at 17:20
  • 1
    Not checking the return value of `fgets()` is a key mistake. Check it and drop using `feof()`. – chux - Reinstate Monica May 17 '21 at 03:47

0 Answers0