Skip to Main Content
ft_printfBack to Top

ft_printf

View on GitHub

A comprehensive implementation of the C standard library printf function. This project’s aim is to take the very simple write command and, using only that, implement the complex features of printf.

Capabilities

Conversions

SpecifierDescription
%cSingle character
%sString of characters
%pPointer address (hex)
%d / %iDecimal (base 10) number
%uUnsigned decimal number
%xHexadecimal number (lowercase)
%XHexadecimal number (uppercase)
%%Percent sign

Flags & Options

FlagDescription
-Left-align the result within the given field width.
0Left-pads numbers with zeros instead of spaces.
.Precision: minimum digits for integers, max characters for strings.
#Alternate form: adds 0x or 0X prefix for hex values.
spacePrepends a blank space before positive numbers.
+Forces a sign (+ or -) to be displayed for signed numbers.
[number]Sets the minimum field width for the output.

Examples

Here is how ft_printf handles complex flag combinations:

Width & Precision

Managing minimum width and specific precision simultaneously.

ft_printf("Result: |%10.5d|\n", 42);
// Output: "Result: |     00042|"
// Width 10, Precision 5 (pads 0s to 5 digits, then spaces to 10 width).

Left Alignment & Padding

Using the minus flag to flip alignment.

ft_printf("Standard: |%10d|\n", 42);
ft_printf("Left-Adj: |%-10d|\n", 42);

// Output:
// Standard: |        42|
// Left-Adj: |42        |

Explicit Signs

Forcing signs on positive numbers.

ft_printf("Signed: %+d\n", 42);
ft_printf("Space:  % d\n", 42);

// Output:
// Signed: +42
// Space:   42

Implementation Details

This project uses a modular “Tokenize & Process” architecture:

  1. Parsing: ft_split_parts separates the format string into literal segments and conversion tokens.
  2. Dispatch: ft_eval_arg routes specific types to their handlers.
  3. Construction: ft_merge_prints calculates total length based on:
    • Left Padding (Width/Flags)
    • Core Content (Precision/Value)
    • Right Padding (Alignment)

Build & Run

Compile the library:

make        # Standard version
make bonus  # With all flags and options

Use in your code:

#include "ft_printf.h"

int main(void)
{
    ft_printf("Hello, %s! You have %d new messages.\n", "Ali", 5);
    return (0);
}