ft_printf

Nine conversions, and the parser that reads them

printf looks simple right up until you write it.

A reimplementation in C, format parser included: nine conversions, the width, precision, padding and sign flags, and variadic arguments read one at a time with va_arg. One pass over the format string, one branch per conversion, and a return value counting the characters written.

Area
  • 42
  • library
  • formatting
Stack
C
Grade
125%
Date
2022

Rewriting one of the best-known functions of the C language, format parser included.

Conversions

%c for a character, %s for a string, %p for a pointer in hexadecimal, %d and %i for a signed decimal, %u for an unsigned one, %x and %X for hexadecimal, and %% for a literal percent sign.

Flags

The bonus part adds a minimum field width on every conversion, and any combination of - to left-justify, 0 to pad with zeroes, . for precision, # for the 0x prefix on hexadecimal, a leading space on positive numbers and + to force the sign.

What it taught me

Variadic functions and va_arg, but above all how to keep a small parser readable: one pass over the format string, one dispatch per conversion, and a return value that counts exactly the characters written.