This project has been created as part of the 42 curriculum by sarfreit.
ft_printf is a 42 project that recreates part of the behavior of the standard printf() function.
It strengthens your skills in:
- handling variadic arguments (
va_list) - manual data formatting
- modular and clean C programming
- implementing flags and reproducing standard printf behavior
Implement the function:
int ft_printf(const char *format, ...);This function:
- Prints formatted output to stdout
- Supports several conversion specifiers
- Returns the number of characters printed
- Reproduces the behavior of the original printf for mandatory conversions
| Specifier | Meaning | Example |
|---|---|---|
%c |
Character | 'A' |
%s |
String | "Hello" |
%p |
Pointer (0x...) or (nil) |
(nil) |
%d |
Signed integer | -42 |
%i |
Signed integer | 24 |
%u |
Unsigned integer | 42 |
%x |
Hexadecimal (lowercase) | 2a |
%X |
Hexadecimal (uppercase) | 2A |
%% |
Prints % |
% |
- Only
write()may be used for printing - Return value = total printed characters
%pprints(nil)when the pointer is NULL- Code must follow the 42 Norm
This project implements the bonus flag set allowed by the subject:
| Flag | Description | Example | Output |
|---|---|---|---|
+ |
Always show the sign | %+d, 42 |
+42 |
(space) |
Leading space for positive numbers | % d, 42 |
42 |
# |
Hexadecimal prefix | %#x, 255 |
0xff |
- If
+andare both used →+wins #only affects%xand%X#does not add prefix when the number is 0
Other flags such as width, precision, -, 0, and * are not implemented.
ft_printfiterates through the format string- When it finds
%, it checks:- flags
- conversion type
- It calls helper functions depending on the type
- It prints numbers, strings, characters, hex, and pointers manually
- It returns the number of characters printed
-
Preparation (Compiling
libftprintf.a):make all
-
Compilation and Linking:
# Link main_mandatory.c against libftprintf.a and libft.a cc -Wall -Wextra -Werror main_mandatory.c libftprintf.a -I . -L libft -lft -o test_mandatory
-
Execution:
./test_mandatory
-
Preparation (Compiling
libftprintf.awith Bonus features):make bonus
-
Compilation and Linking:
# Link main_bonus.c against the bonus libftprintf.a and libft.a cc -Wall -Wextra -Werror main_bonus.c libftprintf.a -I . -L libft -lft -o test_bonus
-
Execution:
./test_bonus
Check for memory leaks:
valgrind --leak-check=full ./test_mandatory
valgrind --leak-check=full ./test_bonusClean the project:
make clean
make fclean
make reFor this project I used the help of some GitBooks from older students, and websites like GeeksforGeeks and W3Schools.