This project has been created as part of the 42 curriculum by ocouto-d.
The ft_printf is a project at 42 School whose main objective is to replicate the functionality of the standard C library function, printf().
Print ARGUMENT(s) according to FORMAT:
%d: Format as a signed decimal integer.
%u: Format as an unsigned decimal integer.
%i: Prints an integer in base 10.
%s: Format as a null-terminated string.
%c: Format as a character.
%x: Format as a hexadecimal number, lowercase.
%X: Format as a hexadecimal number, uppercase.
%p: The void * pointer argument has to be printed in hexadecimal format
%%: Prints a percent sign.
-
To compile the project, execute the make command in the root directory:
This will create the static library libftprintf.a.
-
To use ft_printf in your own code, you must:
Include the header file (ft_printf.h).
Link with the static library during compilation.
-
To compile a main.c file that uses ft_printf:
gcc main.c libftprintf.a -o my_program
CODE EXAMPLE:
#include "ft_printf.h"
int main(void) { int printed_chars; char *name = "42 School";
// Using %s, %d, and %p
printed_chars = ft_printf("Hello, %s! The number is %d. Pointer: %p\n", name, 2024, &printed_chars);
// Printing the returned value
ft_printf("Total characters printed: %d\n", printed_chars);
return (0);
}
- https://vivaolinux.com.br/artigo/Linguagem-C-Funcoes-Variadicas/
- https://stackoverflow.com/questions/26053959/what-does-va-args-in-a-macro-mean
- https://en.cppreference.com/w/c/variadic/va_arg
- https://www.tutorialspoint.com/c_standard_library/c_macro_va_arg.htm
-
Main algorithm: Sequential Processing (Parsing)
The core algorithm of ft_printf is a Stateful Sequential Parsing process, executed as follows:
1.1 - Iteration: The function traverses the format string character by character.
1.2 - Standard State (Literal): If the character is not a %, it is treated as a literal character and is immediately printed to standard output.
1.3 - State Transition (Identifying the %): Upon encountering a %, the algorithm enters the Format Analysis State.
1.4 - Dispatching: The character immediately subsequent to the % (the conversion specifier) is read. This specifier is used as a key for a dispatch mechanism.
1.5 - Converter Execution: The dispatch mechanism (typically a nested if/else if structure or a switch case) calls the specific auxiliary function responsible for handling the associated data type (%d calls the integer function, %s calls the string function, etc.).
1.6 - Return and Counting: The auxiliary function executes the va_arg, conversion, and printing operations, returning the number of characters it printed. This value is added to ft_printf's total character counter.
-
Primary Data Structure: Variable Argument List (va_list)
The fundamental data structure used to manage the arguments is the va_list, defined in the <stdarg.h> library.