Question

I am scanning in a file and counting how many letters are uppercase, lowercase, numbers or other characters; some reason it is giving me segmentation fault; I am not too sure why here is my code

#include<stdio.h>
#include<ctype.h>

int main(void)
{
    FILE *ifp, *ofp;
    char *mode = "r";
    char words;
    int lengthOfWords, i;
    int uppercase=0, lowercase=0, digits=0, other=0, total=0;

    ifp = fopen("story.txt", "r");

    if (ifp == NULL) {
        fprintf(stderr, "Can't open input file in.list!\n");
        return 0;
    }
    else
    {
        while(fscanf("%c", &words) != EOF)
        {
            if ((words>='A')&&(words<='Z'))
            {
                uppercase++;
            }
            else if ((words>='a')&&(words<='z'))
            {
                lowercase++;
            }
            else if ((words>='0')&&(words<='9'))
            {
                digits++;
            }
            else
            {
                other++;
            }
        }
    }
    printf("\n%d %d %d %d\n",uppercase, lowercase, digits, other );



return 0;

}

why I am simply reading it characters by character and counting them as they go

by the way here is my txt file.

The quick Fox jumps
over 2014 *$!&#@] lazy dogs.
Was it helpful?

Solution

You are forgetting to pass a FILE (stream pointer) as a parameter of the fscanf function:

while (fscanf(ifp, "%c", &words) != EOF)

According to the man, the signature of fscanf is:

int fscanf(FILE *restrict stream, const char *restrict format, ...);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top