I have a program written in C which should count the number of times the word “the” appears in text files that are given as arguments.But the program keeps giving a segmentation fault error and I have no more ideas on how to solve this.Any help would be appreciated.Thank you!
Here is the code:
#include <stdio.h>
#include <string.h>
void main(int argc, char *argv[])
{
int h,i;
FILE *fp;
char* mess;
for(i=1; i < argc; i++)
{
h=0;
fp=fopen(argv[i],"r");
while (!feof(fp))
{
fscanf(fp,"%s",mess);
if (strcmp(mess,"the")==0)
h++;
}
printf("The file %s contains the word \"the\" %d times.",argv[i],h);
h=0;
fclose(fp);
}
}
mess is uninitialised. You need to allocate some space for the word you are reading in
so you also want to use the field width to limit what you read to the size of your buffer. This requires a bit of careful handling since the bit after your buffer size just might be “the” (e.g. “breathe”, if you read 4 character words, would give you “brea” and “the” and a false positive)