I am working through the excellent The C Programming Language at the moment, and have got stuck while trying to open and read a file. The program compiles, but seg faults on execution:
$ ./a.out
Segmentation fault
Here is the code:
#include <stdio.h>
main()
{
FILE *fp;
fp=fopen("/home/c-sandbox/index.html", "r");
fprintf(fp, "Testing...\n");
fclose(fp);
}
Note that the path points to a real file containing the string “hello, world”.
Any ideas on where I am going wrong?
You opened the file for reading only, and are attempting to write to it.
Use
"a"if you want to append to the end of the existing file.Edit: As others have noted, you’re also not checking to see if the file was opened.
fopenwill returnNULLif it fails and set the global variableerrnoto a value that indicates why it failed. You can get a human-readable explanation usingstrerror(errno)