Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getchar() and putchar()

in the example:

#include <stdio.h>

main()
{
    long nc;

    nc = 0;
    while (getchar() != EOF)
        ++nc;
    printf("%ld\n", nc);
}

I don't quite understand it. putchar() would put the character out, but why is it that after EOF it puts all the characters out, and where is it remembering all these characters? Thanks.

like image 245
user379229 Avatar asked Feb 02 '10 23:02

user379229


1 Answers

It's called buffering and it's done by the operating system. Usually it does line buffering where it just saves every character you put to it in memory, and then writes it all to the file when it encounters a line break. This saves on resources because file operations take much more time than other operations. So instead of doing output with every single character, it waits for a bunch of characters to collect in the buffer and writes them out all in one go.

It's just a clever maneuver done by the OS that you, the programmer, don't need to worry about. Just throw your characters at it one by one and let the OS handle the rest in its own way.

like image 110
Paige Ruten Avatar answered Sep 17 '22 23:09

Paige Ruten