简体   繁体   中英

Buffer clearing - Output not as expected

C89 C: I've found plenty on getchars and clearerr and but I'm still a little confused. I'm hoping someone can point out we're I'm going wrong.

The code below parses a text file and prints out line per line with the LINEMAX defined as 30. The myFile input file is legit as I get an answer, just not the one I expect.

void printFile(const char* myFile)
{
    /* declare variables */
    char lineString[LINEMAX];
    FILE* lineReader;
    int lineCount;

    /* initialise  */
    lineReader = fopen(myFile, "r");
    lineCount = 1;

    /* parse the text */
    while(fgets(lineString, LINEMAX, lineReader))
    {
        /* check if last character is '\n' */
        if (lineString[strlen(lineString) - 1] != '\n')
        {
            /* check if final line (may not have '\n' character) */
            if(!feof(lineReader))
            {
                printf("ERROR: >30 characters. Buffer overload\n");
                bufferControl(lineReader);
            }
        }
        else
        {
            printf("%d: %s", lineCount++, lineString);
        } 
    }
}

void bufferControl(FILE* lineReader)
{
    int ch;

    /* parse all characters until it runs out of leftover input */
    while ((ch = getchar()) != '\n' && ch != EOF);
    clearerr(lineReader);
}

Now, my input file is simple text file:

Jack Shephard Surgeon
Kate Austen Criminal
Joe Smith Antidisestablishmentarialist
Hurley Reyes Philanthropist
Sun-Hwa Kwon Executive

I am expecting the output to be:

1: Jack Shephard Surgeon
2: Kate Austen Criminal
ERROR: >30 characters. Buffer overload
3: Hurley Reyes Philanthropist
4: Sun-Hwa Kwon Executive

But I get:

1: Jack Shephard Surgeon
2: Kate Austen Criminal
ERROR: >30 characters. Buffer overload
3: tarialist
4: Hurley Reyes Philanthropist
5: Sun-Hwa Kwon Executive

... where at the third line after the 'Buffer overload' I have to press Return to continue (which is probably a clue but I'm not getting it, sorry). My understanding tells me that the bufferControl should remove the 'tarialist' characters but apparently not. Can someone please explain to me what I am misunderstanding. Thanks!

To have this

/* parse all characters until it runs out of leftover input */

become true, you want to replace

while ((ch = getchar()) != '\n' && ch != EOF);

by

while ((ch = fgetc(lineReader)) != '\n' && ch != EOF);

From man getchar() :

getchar () is equivalent to getc ( stdin ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM