I'm having a hard time with a do-while loop, that is supposed to stop when we reach the end of the file. Here's the loop code:
do { if (pcompanyRow[0] != '#' && pass == 1) { strtok(pcompanyRow, ":"); pcompanyName = strcpy(pcompanyName, strtok(NULL, "")); pass = 2; fgets(pcompanyRow, 1024, f); } if (pcompanyRow[0] != '#' && pass == 2) { strtok(pcompanyRow, ":"); pcompanySMSPrice = strcpy(pcompanySMSPrice, strtok(NULL , "")); pass = 3; fgets(pcompanyRow, 1024 , f); } if (pcompanyRow[0] != '#' && pass == 3) { strtok(pcompanyRow, ":"); pcompanyMMSPrice = strcpy(pcompanyMMSPrice, strtok(NULL, "")); pass = 4; fgets(pcompanyRow, 1024, f); } if (pass == 4) { AppendCompanyNode(pcompanyList, pcompanyName, pcompanySMSPrice, pcompanyMMSPrice); pass = 1; } } while (!feof(f)); After running with the debugger, I noticed that all the crash problems I have are because it doesn't go out of this loop even when it reached the whole lines.
How should I write it correctly?
fgets()for example) and you decide that you want to distinguish between EOF and an error. Most often, most people do not bother to distinguish between the two (me specifically, but most of the code I've seen). I don't recall usingfeof()at all - which means I've probably used it a couple of times in the last quarter century of C programming.ferror(f)rather than!feof(f)if you want to know whether an error occurred. Sometimesfeofis useful in do-while loops, but I agree it's pretty useless most of the time.ferror()thanfeof(), but I confess I don't often use that, either. But I should have said so in my comment - or added a second one since I was running out of space.