Search code examples
cloopswhile-loopnested-loopsfgetc

Is this a valid use of fgetc?


My input stream is from a text file with a list of words separated by the \n character. The function stringcompare is a function that will compare the equivalence of two strings, case insensitive.

I have two string arrays, word[50] and dict[50]. word is a string that would be given by the user. Basically what I want to do is pass word[] and each word in the text file as arguments of the stringcompare function.

I've compiled and run this code but it is wrong. Very wrong. What am I doing wrong? Can I even use fgetc() like this? would dict[] even be a string array after the inner loop is done?

        char c, r;
        while((c = fgetc(in)) != EOF){ 
            while((r = fgetc(in)) != '\n'){
                dict[n] = r;
                n++;

            }
            dict[n+1] = '\0'; //is this necessary?
            stringcompare(word, dict);
        }

Solution

  • It is wrong.

    • The return value of fgetc() should be stored to int, not char, especially when it will be compared with EOF.
    • You might forgot to initialize n.
    • You will miss the first character of each line, which is stored to c.
    • Use dict[n] = '\0'; instead of dict[n+1] = '\0'; because n is already incremented in the loop.

    Possible fix:

    int c, r;
    while((c = fgetc(in)) != EOF){ 
        ungetc(c, in); // push the read character back to the stream for reading by fgetc later
        n = 0;
        // add check for EOF and buffer overrun for safety
        while((r = fgetc(in)) != '\n' && r != EOF && n + 1 < sizeof(dict) / sizeof(dict[0])){
            dict[n] = r;
            n++;
    
        }
        dict[n] = '\0'; //this is necessary
        stringcompare(word, dict);
    }