I am working on a simple C program to open a file and read some data from it. There are no compile errors, but when I run the program on a certain file, I get a "Segmentation Fault: code dumped" error. I inserted a print statement at the very top of my code, and it does not get run. Is it possible to get a segmentation fault when you haven't done anything yet?
#include <stdio.h>
int main(int argc, char **argv)
{
printf("%s", "Made it to here!");
FILE *fp;
char input[100];
fp = fopen(argv[1], "r+b");
fgets(input, sizeof(input), fp);
printf("%s", input);
fclose(fp);
return(0);
}
This works when I run it on the text version of itself, it prints out the first line. However, when I run it on another file, texttest.vmf, I get the segmentation fault and the first print doesn't execute. VMFs are Valve Map Files, but they're in standard text format. This file is about 3.7 KB large. Any ideas?
It is not necessary that your code fails before printf
: the call to printf
may have succeeded, but because the output to console is buffered, the program may have crashed before the output has been written to the screen.
Adding \n
to the output string causes console buffer flush. If you are looking to debug by printf
s, you should always add \n
to the end of your format string.
Your fopen
call is likely failing. Try checking the return value before you attempt to use fp
:
FILE *fp;
char input[100];
if((fp = fopen(argv[1], "r+b") == NULL) {
fprintf(stderr, "ERROR: Cannot open file.\n");
return 1;
}
Make sure to add #include <stdlib.h>
for use of the NULL macro.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With