In this project, we're creating our own version of the commonly used printf function in C. This function is all about displaying text in a specific way on the screen. Our aim is to learn how it functions by building our version.
Our custom printf function will take a format string as the first argument, followed by a variable number of additional arguments. The format string will contain placeholders for the data that needs to be printed, and our function will replace these placeholders with the corresponding values from the additional arguments.
-
Function Prototype: Define the function prototype for a custom
printffunction. The function should have a return type ofintand accept aconst char* formatparameter followed by a variable number of arguments using the ellipsis (...) syntax. The return value is the number of characters printed with the function (like regular printf() does). -
Parsing Format String: Implement a mechanism to parse the format string and identify the placeholders. Common placeholders include
%cfor characters,%sfor strings,%dfor integers, etc. -
Handling Placeholders: Once we identify a placeholder, we need to extract the corresponding argument from the variable argument list.
The<stdarg.h>header provides the macros and functions to handle variable arguments. -
Printing: Replace the placeholders in the format string with the actual values and print the formatted output to the console. We used our
_putcharfunction to print individual characters.
_putcharact the same as the standard output functionputchar. -
Edge Cases: Handle edge cases such as invalid format strings, unsupported format specifiers, and other potential errors gracefully.
-
Testing: Create a set of test cases to verify that our custom
printffunction behaves correctly and produces the expected output for various format strings and arguments.
main.h— header file that contains all used functions and custom struct types._printf.c— contains our custom printf implimentationhandlers.c— functions that handle different argument typehelper_functions.c— useful functions such as _putchar()