Search code examples
cfilecharfgetc

I'm trying to read text from a .txt file and count the amount of words in it using c


This is what I have so far. The issue is that the "count" variable is not properly adding to itself when it hits a newline or space character.

#include <stdio.h>
#include <stdlib.h>

int main(void){

    char c;
    int count = 0;
    int* ptr;
    int size;

    FILE *file = fopen("file.txt", "r"); //Reads from input file

    //Test to see if the file exists
    if (file == NULL){
        printf("ERROR 1: TARGET INPUT FILE DOES NOT EXIST, HAS BEEN RENAMED OR HAS BEEN MOVED.");
        exit(1);
    }

    c = fgetc(file);
    while ((c = fgetc(file)) != EOF){

        if(c == " " || c == "\n"){
            count++;
        }

    }

    fclose(file);

    printf("Number of words present in given file: %d", count);  
    return 0;
}

I don't have much of an idea as to why it is failing, although I have looked up multiple sources that have pretty much this exact code that seems to work for them. The output should return a number representing the amount of words in the .txt file.


Solution

  • For starters the variable c should be declared as having type int instead of char.

    Also ths call of fgetc before the while loop

    c = fgetc(file);
    

    is ignored

    You are comparing an integer with pointers

    if(c == " " || c == "\n"){
    

    because string literals in the above expressons are converted to pointers to their first characters. The compiler should issue a message for this if statement.

    But if you will write instead

    if(c == ' ' || c == '\n'){
    

    using character constants nevertheless the approach is incorrect because it does not take into account adjacent spaces.