I am learning the C language from a book. I had reached the part of the book talking about files and command line arguments, but now I'm stuck at the part with this code:
#include <stdio.h>
int main (int argc,char **argv)
{
FILE *f=fopen(argv[1],"r");
int c;
do
{
c=fgetc(f);
printf("%c",c);
}
while(!feof(f));
}
When I run this (with the argument being the code's own file name for testing), an error message appears:
The instruction at 0x0000000000401474 referenced memory at 0x0000000000000006. The memory could not be read. Click on OK to terminate the program. Click on CANCEL to debug the program.
What is the meaning of this error, and how to fix it?
CodePudding user response:
You need to check if the file pointer is not NULL so something like
if (f == NULL) {
return EXIT_FAILURE;
}
Also, files need to be closed when they are done being used.
fclose(f);