ft_printf 🖨️
Regardless of the programming language, printf (or its equivalents) is one of the most useful functions out there. But what if you are not allowed to use printf? That is one of the main rules at Hive Helsinki - except a few standard C library functions, students cannot use the standard C library to complete their projects. It's easy to code one's own putstr and putnbr functions to print strings and numbers to the standard output, but they're uncomparably less convenient than printf.
That's why it was so important to add my own printf to the already extensive C library I previously coded as part of my very first school project.
For more information about this project, check out the project's assignment.
Project Purpose & Goal
Ft_printf was the fourth and the last school project I coded in C, before I moved to web development branch. It was a more advanced one, introducing the concept of variadic functions and ellipsis.
My goal was to create a function that replicates the functionality of the standard printf function. It had to handle multiple format conversions (single characters, strings, pointers, signed and unsigned decimal numbers, octal numbers, hexadecimal numbers, floating point numbers), as well as flags that control how the argument is displayed.
C
Stack & Constraints
The only language allowed for this project was C. I was not allowed to use the official C library, except of four functions: write
, malloc
, free
and exit
. If I needed any other function, I had to code it myself.
To recreate the original printf function, I used my own C library of almost 80 functions, which I coded previously as part of my very first school project.
You can view my C library here. The set of tests I wrote to test proper functionality of the library, including a short shell script that automatically runs all the tests can be found here.
C
Thought Process & Problems
While scheduling out the project workload, I realized that ft_printf will be an invaluable addition to my C library and I would continue extending its functionality for the purpose of future projects. That's why I wanted to keep the code well-structured and easily maintainable. I decided to code the conversions that seemed easier first, such as single characters and strings, and work my way towards the more complex ones.
The most difficult part of this project was replicating the exact behaviour of printf when printing floating point numbers, specifically the accuracy of decimal numbers beyond five decimal places. I also came across several bugs that were difficult to trace at first, because they originated from my own C library I used in this project. I realized how important it is to try and think of as many edge cases as possible and then test thoroughly to make sure even the smallest parts of a larger project work as intended. This experience helped me to improve the library itself, and also my testing and debugging skills.