This is a custom implementation of the C library function printf
for the 42 programming curriculum. The ft_printf
function is used to format and print text to the console.
To use ft_printf
, simply call the function with a format string and any arguments you want to print. The format string can contain conversion specifiers, which are placeholders that tell ft_printf
how to format the arguments.
For example:
#include "ft_printf.h"
int main(void)
{
ft_printf("Hello, %s!\n", "world");
return 0;
}
This will print Hello, world!
to the console.
ft_printf
supports the following conversion specifiers:
Specifier | Description |
---|---|
%c |
Print a single character |
%s |
Print a string |
%d |
Print a signed decimal integer |
%i |
Print a signed decimal integer |
%u |
Print an unsigned decimal integer |
%o |
Print an unsigned octal integer |
%x |
Print an unsigned hexadecimal integer (lowercase) |
%X |
Print an unsigned hexadecimal integer (uppercase) |
%p |
Print a pointer |
%% |
Print a literal % character |
A variadic function is a function in C that accepts a variable number of arguments. This is achieved using the ellipsis (...
) syntax in the function declaration. Printf() is a variadic function by nature because the function doesn't know at compile time how many arguments it will be given. Thus, we must use a variadic function prototype and #include the stdarg.h
library when creating our own ft_printf() function. For example:
int sum(int count, ...);
The ellipsis syntax allows the function to accept any number of arguments after the fixed arguments. To access the variable arguments inside the function, we use the stdarg.h
header and the functions defined within it. The most commonly used functions are:
va_start()
- initializes ava_list
object to point to the first argument after the fixed argumentsva_arg()
- retrieves the next argument of a specified type from theva_list
objectva_end()
- frees any resources associated with theva_list
object
Here's an example of a variadic function that accepts a variable number of integers and returns their sum:
#include <stdarg.h>
int sum(int count, ...) { int i; int sum; va_list args; va_start(args, count); sum = 0; i = -1; while(++i < 3) { sum += va_arg(args, int); } va_end(args); return sum; }
In this example, we first initialize a va_list
object named args
using va_start()
. We then loop through the specified number of arguments and use va_arg()
to retrieve each argument as an integer and add it to the sum
variable. Finally, we free any resources associated with the va_list
object using va_end()
.
Variadic functions are commonly used in C libraries that need to accept a variable number of arguments. The printf()
and scanf()
functions, for example, are variadic functions that are used to format and print input and output.