getchar and putchar

后端 未结 6 1987
耶瑟儿~
耶瑟儿~ 2021-02-06 14:40

My C code:

int c;
c = getchar();

while (c != EOF) {
    putchar(c);
    c = getchar();
}

Why does this program react like this on inputting

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-06 15:10

    When you type, a console grabs the output from the keyboard, echoing it back to you.

    getchar() operates on an input stream, which is typically configured with "Canonical input" turned on. Such a configuration reduces the CPU time spend polling the input for a buffering scheme where the input is buffered, until certain events occur which signal the buffer to expand. Pressing the enter key (and hitting control D) both tend to flush that buffer.

    #include 
    
    int main(void){   
        int c;   
        static struct termios oldt;
        static struct termios newt;
    
        /* Fetch the old io attributes */
        tcgetattr( STDIN_FILENO, &oldt);
        /* copy the attributes (to permit restoration) */
        newt = oldt;
    
        /* Toggle canonical mode */
        newt.c_lflag &= ~(ICANON);          
    
        /* apply the new attributes with canonical mode off */
        tcsetattr( STDIN_FILENO, TCSANOW, &newt);
    
    
        /* echo output */
        while((c=getchar()) != EOF) {
            putchar(c);
            fflush(STDOUT_FILENO);
        }                 
    
        /* restore the old io attributes */
        tcsetattr( STDIN_FILENO, TCSANOW, &oldt);
    
    
        return 0;
    }
    

提交回复
热议问题