>But as Salem often says do not do this...
and quite rightly too. Here's an example of bad coding.
Code:
#include <stdio.h>
#define FILENAME "text.txt"
int main(void)
{
char buffer[1024];
FILE *fileptr;
int lines = 0;
if ((fileptr = fopen(FILENAME, "r")) == NULL)
{
perror(FILENAME);
return (1);
}
while (!feof(fileptr))
{
fgets(buffer, 1024, fileptr);
lines++;
printf ("Line %d of the file is %s", lines, buffer);
}
fclose(fileptr);
return (0);
}
Create a text file called text.txt with say 5 lines of data in it. You'll find that you actually get 6 lines of output. Well, at least that's what happens under some compilers. I have found that some do handle it differently. Therefore it is best not to use code like this.