This project has been created as part of the 42 curriculum by mju-ferr.
ft_printf is a recreation of the standard C library function printf(). This project is designed to deepen understanding of variadic functions in C and help consolidate knowledge from other projects, through the implementation of a versatile and well-structured output formatting function.
The goal is to implement a function that mimics the behavior of the original printf(), handling various format specifiers and returning the number of characters printed.
To compile the project, simply run:
makeThis will generate the libftprintf.a library file.
- To remove object files:
make clean - To remove object files and the library:
make fclean - To recompile everything:
make re
Include the header file in your C program:
#include "ft_printf.h"Link the library when compiling your program:
cc your_program.c -L. -lftprintf#include "ft_printf.h"
int main(void)
{
ft_printf("Hello %s!\n", "World");
ft_printf("Number: %d\n", 42);
ft_printf("Hex: %x\n", 255);
return (0);
}%c- Print a single character%s- Print a string%p- Print a pointer in hexadecimal format%d- Print a decimal (base 10) number%i- Print an integer in base 10%u- Print an unsigned decimal (base 10) number%x- Print a number in hexadecimal (base 16) lowercase%X- Print a number in hexadecimal (base 16) uppercase%%- Print a percent sign
The implementation uses a parser-based approach with the following structure:
- Main Parser Loop: The
ft_printf()function iterates through the format string character by character - Format Handler: When a
%is encountered, theft_handle_format()function is called to process the conversion specifier - Specialized Converters: Each conversion type has its own dedicated function for clarity and maintainability
Variadic Arguments: Uses the <stdarg.h> library functions:
va_start()- Initialize the argument listva_arg()- Retrieve the next argumentva_end()- Clean up the argument list
Character Count Tracking: Each function returns the number of characters printed, which are accumulated and returned by ft_printf()
Edge Case Handling:
- NULL string pointers print "(null)"
- NULL pointers print "(nil)"
- Negative numbers are handled with sign conversion
ft_printf.c- Main function and format handlerft_printf_char.c- Character and string conversionsft_printf_nbr.c- Integer and unsigned integer conversionsft_printf_hex.c- Hexadecimal and pointer conversionsft_printf.h- Header file with function prototypes
- printf man page - Official printf documentation
- stdarg.h man page - Variadic functions documentation
- 42 Norm - 42 School coding standards
AI was used as a learning assistant for:
- Understanding the technical details of variadic functions in C
- Clarifying edge cases for different conversion specifiers (e.g., NULL pointer behavior)