Search code examples
c++coutputstream

what does printf or any output function actually do?


I want to know that all these output functions, basically what do they do? Because I have experienced many times that printf doesn't always print on screen at the time it is encountered and I have heard that it puts in buffer or something like that. So if someone can make it clear that actually what happens. It would be good if same information about input functions can also be given.. The deeper you tell it will be much helpful. . Thanks.


Solution

  • Printf

    Writes the C string pointed by format to the standard output (stdout). If format includes format specifiers (subsequences beginning with %), the additional arguments following format are formatted and inserted in the resulting string replacing their respective specifiers.

    This has been well explained here that how printf actually works:

    1. Your software calls printf().

    2. printf() processes your string, and args, and then needs to execute a kernel function, as writing to a file can't be done in ring 3.

    3. printf() generates a software interrupt, placing in a register the number of a kernel function (in that case, the write() function).

    4. The software execution is interrupted, and the instruction pointer moves to the kernel code. So we are now in ring 0, in a kernel function.
    5. The kernel process the request, writing to the file (stdout is a file descriptor).

    6. When done, the kernel returns to the software's code, using the iret instruction.

    7. The software's code continues.

    Some useful lines from ISO C99 section 7.19.3/3

    When a stream is unbuffered, characters are intended to appear from the source or at the destination as soon as possible. Otherwise characters may be accumulated and transmitted to or from the host environment as a block.

    When a stream is fully buffered, characters are intended to be transmitted to or from the host environment as a block when a buffer is filled.

    When a stream is line buffered, characters are intended to be transmitted to or from the host environment as a block when a new-line character is encountered.

    Furthermore, characters are intended to be transmitted as a block to the host environment when a buffer is filled, when input is requested on an unbuffered stream, or when input is requested on a line buffered stream that requires the transmission of characters from the host environment.

    Support for these characteristics is implementation-defined, and may be affected via the setbuf and setvbuf functions.