Reputation: 380
int main(int argc, char ** argv) {
int MAX_LINE = 66;
//user does not enter a file name
if(argc == 1) {
printf("Please enter a file name\n");
exit(0);
}
//if user enters too many args
if(argc > 2) {
printf("Please only one file name\n");
exit(0);
}
//grab file name to check if it exists
char *filename = argv[1];
char line[128];
//fileopening
FILE *fileopen;
//file exists, read in line
if(fopen(filename, "r")) {
while(fgets(line, sizeof line, fileopen) != NULL) {
}
}
//the file does not exist
else {
printf("File does not exist\n");
exit(0);
}
return 0;
}
Hey everybody, I had a question about file i/O in C, specifically fgets. I want to learn a little more about parsing a file line by line, but my file returns a Segmentation fault on fgets. I know a segmentation fault means that a pointer is pointing to nothing, but I am not sure where fgets would be returning a pointer to nothing. Can someone tell me why it would be doing this?
My file is one line text file that says 123 test.
Thank you
Upvotes: 0
Views: 1003
Reputation: 26
fileopen is uninitialized. It so happens to be null in your case, triggering the segmentation fault.
fileopen = open(filename, "r");
if (fileopen)
{
while (...)
{
}
}
Upvotes: 1