简体   繁体   中英

Unexpected fgets behavior on EOF

I have this code that gets a line from stdin:

char string[USR_SIZE+1];
/*USR_SIZE is 9 */ 
fgets(string, USR_SIZE, stdin);
size_t len = strlen(string);
if (string[len-1] == '\n') {
    // read in whole line, no need to clear buffer
    string[len-1] = 0;
}    
else {
    if(feof(stdin)){
        printf("EXACT LEN\n");
    }
    else{
        //username too long, clear stdin and retry
        printf("Dumping...");
        dump_line(stdin); //clear stdin
        /*something that loops until success*/

    }

}

No newline in the buffer string means either EOF or that the string was cut.

Now. The optimal string needed is like "user_123" (8 char). Now if I type "user_12345678" it correctly stores only "user_123" and executes the else body. If I type "user_123" it executes else body too.

I want to distinguish a "user_123" ( EOF ) string from a "user_1234" (cutted) because of only in this last case input is not correct. Why feof is not set ?

Furthermore: how i can check fgets return value for error managament?

Found this solution:

if (fgets(string, USR_SIZE + 1, stdin)){
    if (strlen(string) == USR_SIZE && string[USR_SIZE - 1] == '\n'){
        printf("EXACT\n");
        /* User entered an eight character string. */
        string[USR_SIZE - 1] = 0;
    }
    else{
        if(strlen(string) < USR_SIZE-1){
        printf("INVALID<<<\n");
        /*don't dump*/
    }
        else{
            printf("INVALID>>>\n");
            dump_line(stdin);
        }
    }

    printf("EXIT\n");
    printf("%s\n", string);
}
else{
    free(auth_data);
    EXIT_ON_ERROR_("Error while getting user input\n");
}

Something like this would work, if you want to allow for 8 characters and EOF as well as a newline:

char buf[10];
fgets(buf, 10, stdin);

int len=strlen(buf);
if (buf[len-1] == '\n') buf[len-1] = '\0';
if (strlen(buf) == 8)
    puts("Correct length");
else
    puts("Incorrect length");

( fgets isn't tested for success in this example)

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