Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does printf work internally? [duplicate]

I am curious as to how printf works internally within Linux. I don't understand how it writes data to STDOUT.

After a bit of searching for the internals, I downloaded glibc and took a look at the source code:

__printf (const char *format, ...)
{
   va_list arg;
   int done;

   va_start (arg, format);
   done = vfprintf (stdout, format, arg);
   va_end (arg);

   return done;
}

After finding this, I went deeper into the vfprintf function - but the file is about 2500 lines of unfamiliar C code. I'm looking for an explanation from 10,000 feet of how printf works with a computer's memory and output to display characters on screen.

If I were a piece of assembly code what would I have to do to accomplish the same task? Is it operating system dependent?

like image 442
sdasdadas Avatar asked Aug 16 '13 18:08

sdasdadas


People also ask

How does the printf function work?

The printf function (the name comes from “print formatted”) prints a string on the screen using a “format string” that includes the instructions to mix several strings and produce the final string to be printed on the screen.

What happens inside printf?

The printf() function sends a formatted string to the standard output (the display). This string can display formatted variables and special control characters, such as new lines ('\n'), backspaces ('\b') and tabspaces ('\t'); these are listed in Table 2.1.

How does printf work in assembly?

Printf in Assembly To call printf from assembly language, you just pass the format string in rdi as usual for the first argument, pass any format specifier arguments in the next argument register rsi, then rdx, etc.

How does scanf and printf work?

The scanf("%d",&number) statement reads integer number from the console and stores the given value in number variable. The printf("cube of number is:%d ",number*number*number) statement prints the cube of number on the console.


1 Answers

I think you're looking at the wrong layer. The logic in vfprintf is responsible for formatting its arguments and writing them through the underlying stdio functions, usually into a buffer in the FILE object it's targetting. The actual logic for getting this output to the file descriptor (or on other non-POSIX-like systems, the underlying device/file representation) is probably in fwrite, fputc, and/or some __-prefixed internal functions (perhaps __overflow).

like image 128
R.. GitHub STOP HELPING ICE Avatar answered Nov 15 '22 12:11

R.. GitHub STOP HELPING ICE