You cannot compare strings in C. You should compare them character by character using the standard library function strcmp. Here's its prototype contained in the string.h header.
int strcmp(const char *s1, const char *s2);
The strcmp function compares the two strings s1 and s2. It returns an integer less than, equal to, or greater than zero if s1 is found, respectively, to be less than, to match, or be greater than s2.
The format string of fscanf " %s " (note the trailing and the leading space) will read and discard any number of whitespaces which it does anyway with the format string "%s". This means no whitespaces will be written into the buffer words by fscanf. fscanf will write only non-whitespace characters in words and returns when it encounters a whitespace. So, to count the number of words, just increase the counter for each successful fscanf call.
Also, your program should check for possible buffer overflow in scanf and fscanf calls. If the input string is too big for the buffer, then this would cause undefined behaviour and even causing crash due to segfault. You can guard against it by changing the format string. scanf("%63s", filename); means scanf will read from stdin until it encounters a whitespace and write at most 63 non-whitespace characters in the buffer filename and then add a terminating null byte at the end.
#include <stdio.h>
#include <string.h>
int main(void) {
// assuming max word length is 256
// +1 for the terminating null byte added by scanf
char words[256 + 1];
// assuming max file name length is 64
// +1 for the terminating null byte
char filename[64 + 1];
int count = 0; // counter for number of words
printf("Enter the file name: ");
scanf("%64s", filename);
FILE *fileptr;
fileptr = fopen(filename, "r");
if(fileptr == NULL)
printf("File not found!\n");
while((fscanf(fileptr, "%256s", words)) == 1)
count++;
printf("%s contains %d words.\n", filename, count);
return 0;
}
wordsis a string(or char array) and you are comparing it with a single char. Instead try strcmp(words," ") and strcmp(words,"\n");%sdoes not contain white spaces(e.g.''or'\ n').while ((fscanf(fileptr, "%s", words))> 0) { count++; }