Skip to content
man-YoctoPublic

About

printf reimplemented from scratch in C with variadic arguments

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

ft_printf

A reimplementation of the C standard library's printf, built as a static library (libftprintf.a).

Built as part of the 42 curriculum.

Supported conversions

Specifier Output
%c a single character
%s a string
%p a pointer address in hexadecimal (0x…)
%d / %i a signed decimal integer
%u an unsigned decimal integer
%x / %X an unsigned hexadecimal integer (lower / upper case)
%% a literal percent sign

Like the original, ft_printf returns the number of characters printed.

Build & use

make            # builds libftprintf.a
make clean / fclean / re
#include "ft_printf.h"

int main(void)
{
    int n = ft_printf("%s is %d years old (%x in hex) at %p\n", "Ahmad", 21, 21, &n);
    ft_printf("printed %d chars\n", n);
}
cc main.c -L. -lftprintf

How it works

ft_printf walks the format string, writing ordinary characters directly. When it meets %, it passes the next character and the va_list to ft_format_handler, which dispatches to a small printer for each type (ft_putchar, ft_putstr, ft_putnbr, ft_putunbr, ft_putptr) and returns how many characters it wrote. Hexadecimal output goes through a generic base-conversion routine, ft_putnbr_base, which takes the digit set (0123456789abcdef or …ABCDEF) as a parameter.

Key technical challenges

  • Variadic functions — reading arguments of different types safely with va_start, va_arg and va_end.
  • Accurate return value — counting every byte written across all conversions.
  • Edge cases — INT_MIN, pointer formatting, and unsigned conversions of negative values.

What I learned

About

printf reimplemented from scratch in C with variadic arguments

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages