Reputation: 11
I'm trying to run a program that finds the word count for a file. Every time I compile the program it gives me a Segmentation Fault(Core Dumped). Can't figure out why.
#include <stdio.h>
int main(int argc, char* argv[]){
int wc = 1;
FILE *input = fopen(argv[1],"r");
char c = fgetc(input);
while(c != EOF){
if(c == ' '){
wc++;
}
else
c = fgetc(input);
}
fclose(input);
printf("Word Count = %d", wc);
return 0;
}
Upvotes: 0
Views: 197
Reputation: 224102
You're probably segfaulting because you're not passing in a file name on the command line. When you do that, argv[1]
is NULL, so fopen
is dereferencing a NULL pointer.
You pass the file name to your program on the command line like this:
./my_program file_to_test
To prevent the core dump, you should check that an argument was passed in by checking the value of argc
. You should also check the return value of fopen
to ensure the file was opened:
if (argc < 2) {
printf("no file name given");
exit(1);
}
FILE *input = fopen(argv[1],"r");
if (input == NULL) {
perror("fopen failed");
exit(1);
}
Then you have another problem:
if(c == ' '){
wc++;
}
else
c = fgetc(input);
When you find a space character, you don't attempt to read the next character. So c
doesn't change once a space is read, leading to an infinite loop.
You need to get rid of the else
and always call fgetc
:
if(c == ' '){
wc++;
}
c = fgetc(input);
Also, the fgetc
function returns an int
(actually an unsigned char
cast to an int
), so you should declare c
as an int
. Otherwise, checking it against EOF
can fail.
Upvotes: 1