Search code examples
cfunctionfgets

How to use fgets() function so that it only reads 12 characters per line?


I have a file that contains the following words:

Theendsherethiswillnotjaksdjlasdfjkl;asdjfklasdjfkl;asdfjl;
these
are
the

Below is my code :

int i = 0;
    bool duplicateFound = false;
        while(fgets(line,12,fp)){
            for (int j = 0; j < i; j++){
                if (strcmp(wordList[j], line) == 0){
                    duplicateFound = true;
                    printf("Duplicate Found on Line %d : %s\n", j, wordList[j]);
                }
            }
            if (duplicateFound == false){
                strcpy(wordList[i], line);
                printf("%s", wordList[i]);
            }
            i++;*/

            printf("%s", line);
        }

I am using line to save each word so that I can later check it for duplicates in the array. I want it so that the function only reads up to 12 characters on each line but it outputs the following output.

ACTUAL OUTPUT :

Theendsherethiswillnotjaksdjlasdfjkl;asdjfklasdjfkl;asdfjl;
these
are
the

EXPECTED OUTPUT:

Theendsheret
these
are
the

Solution

  • You really should just call fgets and then do line[12] = '\0', but that doesn't cleanly deal with input that has long lines. One option is to simply abort if fgets ever returns a partial line (eg, if strchr(line, '\n') returns NULL). If you want to handle long lines, you can just discard data with getchar until you see a newline. Assuming that you don't want to consider the newline to be one of the 12 characters, you could do something like:

    #include <stdio.h>
    #include <string.h>
    
    int
    main(void)
    {
            char line[13];
            while( fgets(line, 13, stdin) ) {
                    char *c = strchr(line, '\n');
                    int ch;
                    if( c == NULL ) while( (ch = getchar()) != EOF ) {
                            if( ch == '\n' ) {
                                    break;
                            }
                    } else {
                            *c = '\0';
                    }
                    if( printf("%s\n", line) < 0 ) {
                            break;
                    }
            }
            return ferror(stdout) || ferror(stdin) || fclose(stdout) || fclose(stdin);
    }