Don't use feof()
, see Why is “while ( !feof (file) )” always wrong? .
Check the return value of fopen()
whether fopen()
was success or failed, if fopen()
returns NULL
then don't proceed further or don't do any operation with p
. for e.g
FILE *p = fopen("data.txt11", "r");
if (p == NULL) {
fprintf(stderr,"file doesn't exist\n");
return 0;
}
And check the return value of fgets()
. From the manual page of fgets()
RETURN VALUE
fgets()
return s
on success, and NULL
on error or when end
of file occurs while no characters have been read.
for e.g
char *ptr = NULL;
while( (ptr = fgets(ar,sizeof(ar), p)) != NULL) {
printf("%s",ptr);
/* fgets() copies \n t the end of buffer, if you don't want remove it by some logic */
}
About what fgets()
will read, from the manual page
fgets()
reads in at most one less than size
characters from stream
and
stores them into the buffer
pointed to by s. Reading stops after an
EOF
or a newline
. If a newline is read, it is stored
into the buffer.