ft_printf 79 commits

readme

364 lines 11 kB

This project has been created as part of the 42 curriculum by mleitao.

Description

A custom implementation of the C standard library printf function, supporting formatted output with flags, width, precision, and multiple specifiers.

Built as a static library (libftprintf.a) for easy integration into various C projects.

Prototype

This implementation aims to replicate the behavior of the standard printf function.

int	ft_printf(const char *fmt, ...);

Instructions

Requirements

  • A C compiler, ideally clang.
  • make.

Makefile

CommandDescription
make, make all, make libftprintf.a, make bonusBuild the libftprintf.a static library
make cleanRemove the build/ directory
make fcleanRemove the build/ directory and the library
make reRebuild the library (equivalent to make fclean followed by make)

Usage

  1. Clone the repository:

    git clone ssh://git@codeberg.org/6times7/ft_printf.git
    
  2. Build the library:

    make -C ft_printf
    
  3. Include the header in your source file:

    #include <ft_printf.h>
    
  4. Compile your program with the library:

    cc main.c -Ipath/to/header -Lpath/to/library -lftprintf
    

Example Usage

Example program main.c:

#include <ft_printf.h>

int	main(void)
{
    ft_printf("hello %s\n", "world!");
  	return (0);
}

Compile it with the library and header:

cc main.c -Ipath/to/header -Lpath/to/library -lftprintf -o yippie

Run it:

./yippie

Expected output:

hello world!

Format Specification

The format specification is as follows:

% Flags Field width Precision Specifier
Required Optional Optional Optional Required

The precision field is introduced by a ..

The general format of a conversion specification is:

%[flags][width][.precision]specifier

This function supports several format specifiers, described below.

Flags

- Left justifies the converted value within the field, appending it with blanks (spaces). By default, it is right justified.
+ Prepends the converted value with a plus or minus sign (+ or -), even for positive numbers. By default, only negative numbers are prepended with a sign.
(space) Prepends the converted value with a space if it is a positive number. Ignored if the flag '+' is set.
# Prepends the converted value for specifiers x and X with 0x or 0X, respectively, if the value is different than zero.
0 Prepends the converted value for specifiers d, i, u, x and X with zeros instead of spaces. Ignored if the flag '-' is set or if precision is defined.

Field width

number Minimum number of characters to be printed. If the converted value is shorter than the specified width, it is prepended with spaces (or appended if the '-' flag is set). The value is not truncated.
* The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.

Precision

.number For integer specifiers (d, i, u, x, X), precision specifies the minimum number of digits to be written. If the value is shorter, the result is padded with leading zeros. The value is not truncated. A precision of 0 means that no character is written for the value 0.
For s, precision specifies the maximum number of characters to be printed.
If the period is specified without a value, 0 is assumed.
.* The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.

Specifiers

% Writes the character %.
c Writes a single character.
s Writes a character string.
p Writes an implementation-defined character sequence representing a pointer address.
d or i Writes a signed integer in decimal representation.
u Writes an unsigned integer in decimal representation.
x or X Writes an unsigned integer in hexadecimal representation.

Design and Implementation

Overview

This implementation of ft_printf parses the format string sequentially and each conversion specification independently.

Project Structure

This project is organized into modular components to separate parsing, printing and utility logic.
Each part of this implementation is isolated in its own directory to improve readability, maintainability, and scalability.

The following tree outlines the overall structure:

.
├── compile_flags.txt
├── include
│   ├── core_bonus.h
│   ├── dispatcher_bonus.h
│   ├── ft_printf.h
│   ├── parser_bonus.h
│   ├── printers_bonus.h
│   └── utils.h
├── Makefile
├── README.md
└── src
    ├── dispatcher
    │   └── dispatch_bonus.c
    ├── ft_printf.c
    ├── parser
    │   ├── parse_format_bonus.c
    │   └── parse_utils_bonus.c
    ├── printers
    │   ├── format_number_bonus.c
    │   ├── format_padding_bonus.c
    │   ├── print_c_bonus.c
    │   ├── print_diu_bonus.c
    │   ├── print_hex_bonus.c
    │   ├── print_number_bonus.c
    │   ├── print_percent_bonus.c
    │   └── print_s_bonus.c
    └── utils
        ├── char.c
        ├── io.c
        ├── memory.c
        ├── numbers.c
        └── string.c

Parsing Strategy

The format string is processed until the first occurrence of the character %. If it is encountered, all subsequent characters up to the specifier are parsed to extract:

  • Flags
  • Field width
  • Precision
  • Specifier

Parsing stops once a valid specifier is found, and the collected information is stored in a structure for later use in formatting the output.
If no valid specifier is found, the behavior is considered undefined according to the C89 standard, Appendix A.6.2. This implementation adopts a permissive approach to such cases: invalid sequences are printed as-is and parsing continues.

Data Structures

A structure is used to represent a parsed conversion specification.
It contains fields for each flag, as well as width, precision, and the specifier.

typedef struct s_format
{
	int		minus;
	int		zero;
	int		hash;
	int		plus;
	int		space;
	long	width;
	long	precision;
	char	spec;
}			t_format;

Additionally, another structure is used to maintain state across the formatting process.
It stores the current position in the format string, the number of characters written, the list of arguments, and an instance of the conversion specification structure.

typedef struct s_data
{
	int			chars_written;
	const char	*fmt;
	va_list		args;
	t_format	format;
}	t_data;

For numeric conversions, a dedicated structure stores all information required for formatting.
This includes the string representation of the number, its length, sign information, padding information, and, for the x, X and p specifiers, the associated prefix and its length.

typedef struct s_num
{
	char	*num;
	int		len;
	int		is_negative;
	char	sign;
	int		zeros;
	int		spaces;
	char	*prefix;
	int		prefix_len;
}			t_numdata;

Execution Flow

    flowchart LR;
    start@{ shape: stadium, label: "Start" }
    
    start --> scan[Scan string]

    scan --> found{Found '%'?}
    
    found --> |Yes| writeuntil[Write string up until '%']
    found --> |No| writeentire[Write remaining of string]

    writeuntil --> |OK| parse[Parse]
    writeuntil --> |ERROR| FAILEND
    
    writeentire --> |OK| SUCCEND
    writeentire --> |ERROR| FAILEND
    
    parse --> |OK| dispatch[Dispatch]
    parse --> |ERROR| writepercent[Write '%']

    writepercent --> |OK| scan
    writepercent --> |ERROR| FAILEND

    dispatch --> |OK| print[Print format]
    dispatch --> |ERROR| FAILEND

    print --> |OK| scan
    print --> |ERROR| FAILEND

    SUCCEND@{ shape: stadium, label: "Successful exit" }
    FAILEND@{ shape: stadium, label: "Failure exit" }

Resources

References

LLM Usage

LLMs were used for:

  • Project structure
  • Design decisions
  • Parts of this README

Tests

This project was tested against printfTester. Kudos to @Tripouille for providing this test suite.

  1*This project has been created as part of the 42 curriculum by mleitao.*
  2
  3<h1 id="description">Description</h1>
  4
  5A custom implementation of the C standard library `printf` function, supporting formatted output with flags, width, precision, and multiple specifiers.
  6
  7Built as a static library (```libftprintf.a```) for easy integration into various C projects.
  8
  9<h3 id="prototype">Prototype</h3>
 10
 11This implementation aims to replicate the behavior of the standard `printf` function.
 12
 13```c
 14int	ft_printf(const char *fmt, ...);
 15```
 16
 17<h1 id="instructions">Instructions</h1>
 18
 19<h3 id="requirements">Requirements</h3>
 20
 21- A C compiler, ideally `clang`.
 22- `make`.
 23
 24<h3 id="makefile">Makefile</h3>
 25
 26Command | Description
 27--|--
 28`make`, `make all`, `make libftprintf.a`, `make bonus` | Build the `libftprintf.a` static library
 29`make clean` |  Remove the `build/` directory
 30`make fclean` | Remove the `build/` directory and the library
 31`make re` | Rebuild the library (equivalent to `make fclean` followed by `make`)
 32
 33<h3 id="usage">Usage</h3>
 34   
 351. Clone the repository:
 36   ```bash
 37   git clone ssh://git@codeberg.org/6times7/ft_printf.git
 38   ```
 39
 402. Build the library:
 41   ```bash
 42   make -C ft_printf
 43   ```
 44
 453. Include the header in your source file:
 46   ```c
 47   #include <ft_printf.h>
 48   ```
 49
 504. Compile your program with the library:
 51   ```bash
 52   cc main.c -Ipath/to/header -Lpath/to/library -lftprintf
 53   ```
 54
 55<h3 id="example-usage">Example Usage</h3>
 56
 57Example program `main.c`:
 58
 59```c
 60#include <ft_printf.h>
 61
 62int	main(void)
 63{
 64    ft_printf("hello %s\n", "world!");
 65  	return (0);
 66}
 67```
 68
 69Compile it with the library and header:
 70
 71```bash
 72cc main.c -Ipath/to/header -Lpath/to/library -lftprintf -o yippie
 73```
 74
 75Run it:
 76
 77```bash
 78./yippie
 79```
 80
 81Expected output:
 82
 83```
 84hello world!
 85```
 86
 87<h1 id="format_specification">Format Specification</h1>
 88
 89The format specification is as follows:
 90
 91<table>
 92  <tr>
 93    <td align="center"><b>%</b></td>
 94    <td align="center"><b>Flags</b></td>
 95    <td align="center"><b>Field width</b></td>
 96    <td align="center"><b>Precision</b></td>
 97    <td align="center"><b>Specifier</b></td>
 98  </tr>
 99  <tr>
100    <td align="center"><b>Required</b></td>
101    <td align="center">Optional</td>
102    <td align="center">Optional</td>
103    <td align="center">Optional</td>
104    <td align="center"><b>Required</b></td>
105  </tr>
106</table>
107
108The precision field is introduced by a `.`.
109
110The general format of a conversion specification is:
111
112```
113%[flags][width][.precision]specifier
114```
115
116This function supports several format specifiers, described below.
117
118<table>
119    <tr>
120        <th colspan=2><h3>Flags</h3></th>
121    </tr>
122    <tr>
123        <td align="center">-</td>
124        <td>Left justifies the converted value within the field, appending it with blanks (spaces). By default, it is right justified.</td>
125    </tr>
126    <tr>
127        <td align="center">+</td>
128        <td>Prepends the converted value with a plus or minus sign (+ or -), even for positive numbers. By default, only negative numbers are prepended with a sign.</td>
129    </tr>
130    <tr>
131        <td align="center">(space)</td>
132        <td>Prepends the converted value with a space if it is a positive number. Ignored if the flag '+' is set.</td>
133    </tr>
134    <tr>
135        <td align="center">#</td>
136        <td>Prepends the converted value for specifiers <b>x</b> and <b>X</b> with 0x or 0X, respectively, if the value is different than zero.</td>
137    </tr>
138    <tr>
139        <td align="center">0</td>
140        <td>Prepends the converted value for specifiers <b>d</b>, <b>i</b>, <b>u</b>, <b>x</b> and <b>X</b> with zeros instead of spaces. Ignored if the flag '-' is set or if precision is defined.</td>
141    </tr>
142    <tr>
143    	<th colspan=2><h3>Field width</h3></th>
144    </tr>
145    <tr>
146        <td align="center">number</td>
147        <td>Minimum number of characters to be printed. If the converted value is shorter than the specified width, it is prepended with spaces (or appended if the '-' flag is set). The value is not truncated.</td>
148    </tr>
149    <tr>
150        <td align="center">*</td>
151        <td>The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.</td>
152    </tr>
153    <tr>
154    	<th colspan=2><h3>Precision</h3></th>
155    </tr>
156    <tr>
157        <td align="center">.number</td>
158        <td>For integer specifiers (<b>d</b>, <b>i</b>, <b>u</b>, <b>x</b>, <b>X</b>), precision specifies the minimum number of digits to be written. If the value is shorter, the result is padded with leading zeros. The value is not truncated. A precision of 0 means that no character is written for the value 0.</br>
159        For <b>s</b>, precision specifies the maximum number of characters to be printed.</br>
160        If the period is specified without a value, 0 is assumed.</td>
161    </tr>
162    <tr>
163        <td align="center">.*</td>
164        <td>The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.</td>
165    </tr>
166    <tr>
167        <th colspan=2><h3>Specifiers</h3></th>
168    </tr>
169    <tr>
170        <td align="center">%</td>
171        <td>Writes the character %.</td>
172    </tr>
173    <tr>
174        <td align="center">c</td>
175        <td>Writes a single character.</td>
176    </tr>
177    <tr>
178        <td align="center">s</td>
179        <td>Writes a character string.</td>
180    </tr>
181    <tr>
182        <td align="center">p</td>
183        <td>Writes an implementation-defined character sequence representing a pointer address.</td>
184    </tr>
185    <tr>
186        <td align="center">d or i</td>
187        <td>Writes a signed integer in decimal representation.</td>
188    </tr>
189    <tr>
190        <td align="center">u</td>
191        <td>Writes an unsigned integer in decimal representation.</td>
192    </tr>
193    <tr>
194        <td align="center">x or X</td>
195        <td>Writes an unsigned integer in hexadecimal representation.</td>
196    </tr>
197</table>
198
199<h1 id="design_implementation">Design and Implementation</h1>
200
201<h3 id="overview">Overview</h3>
202
203This implementation of `ft_printf` parses the format string sequentially and each conversion specification independently.
204
205<h3 id="project_structure">Project Structure</h3>
206
207This project is organized into modular components to separate [parsing](./src/parser/), [printing](./src/printers/) and [utility](./src/utils/) logic. \
208Each part of this implementation is isolated in its own directory to improve readability, maintainability, and scalability.
209
210The following tree outlines the overall structure:
211
212```bash
213.
214├── compile_flags.txt
215├── include
216│   ├── core_bonus.h
217│   ├── dispatcher_bonus.h
218│   ├── ft_printf.h
219│   ├── parser_bonus.h
220│   ├── printers_bonus.h
221│   └── utils.h
222├── Makefile
223├── README.md
224└── src
225    ├── dispatcher
226    │   └── dispatch_bonus.c
227    ├── ft_printf.c
228    ├── parser
229    │   ├── parse_format_bonus.c
230    │   └── parse_utils_bonus.c
231    ├── printers
232    │   ├── format_number_bonus.c
233    │   ├── format_padding_bonus.c
234    │   ├── print_c_bonus.c
235    │   ├── print_diu_bonus.c
236    │   ├── print_hex_bonus.c
237    │   ├── print_number_bonus.c
238    │   ├── print_percent_bonus.c
239    │   └── print_s_bonus.c
240    └── utils
241        ├── char.c
242        ├── io.c
243        ├── memory.c
244        ├── numbers.c
245        └── string.c
246```
247
248<h3 id="parsing_strategy">Parsing Strategy</h3>
249
250The format string is processed until the first occurrence of the character `%`. If it is encountered, all subsequent characters up to the specifier are parsed to extract:
251
252- Flags
253- Field width
254- Precision
255- Specifier
256
257Parsing stops once a valid specifier is found, and the collected information is stored in a structure for later use in formatting the output. \
258If no valid specifier is found, the behavior is considered undefined according to the [C89 standard, Appendix A.6.2](https://port70.net/~nsz/c/c89/c89-draft.html#A.6.2). This implementation adopts a permissive approach to such cases: invalid sequences are printed as-is and parsing continues.
259
260<h3 id="data_structures">Data Structures</h3>
261
262A [structure](./include/core_bonus.h) is used to represent a parsed conversion specification. \
263It contains fields for each flag, as well as width, precision, and the specifier.
264
265```c
266typedef struct s_format
267{
268	int		minus;
269	int		zero;
270	int		hash;
271	int		plus;
272	int		space;
273	long	width;
274	long	precision;
275	char	spec;
276}			t_format;
277```
278
279Additionally, another [structure](./include/core_bonus.h) is used to maintain state across the formatting process. \
280It stores the current position in the format string, the number of characters written, the list of arguments, and an instance of the conversion specification structure.
281
282```c
283typedef struct s_data
284{
285	int			chars_written;
286	const char	*fmt;
287	va_list		args;
288	t_format	format;
289}	t_data;
290```
291
292For numeric conversions, a dedicated [structure](./include/printers_bonus.h) stores all information required for formatting. \
293This includes the string representation of the number, its length, sign information, padding information, and, for the `x`, `X` and `p` specifiers, the associated prefix and its length.
294
295```c
296typedef struct s_num
297{
298	char	*num;
299	int		len;
300	int		is_negative;
301	char	sign;
302	int		zeros;
303	int		spaces;
304	char	*prefix;
305	int		prefix_len;
306}			t_numdata;
307```
308
309<h3 id="execution_flow">Execution Flow</h3>
310
311```mermaid
312    flowchart LR;
313    start@{ shape: stadium, label: "Start" }
314    
315    start --> scan[Scan string]
316
317    scan --> found{Found '%'?}
318    
319    found --> |Yes| writeuntil[Write string up until '%']
320    found --> |No| writeentire[Write remaining of string]
321
322    writeuntil --> |OK| parse[Parse]
323    writeuntil --> |ERROR| FAILEND
324    
325    writeentire --> |OK| SUCCEND
326    writeentire --> |ERROR| FAILEND
327    
328    parse --> |OK| dispatch[Dispatch]
329    parse --> |ERROR| writepercent[Write '%']
330
331    writepercent --> |OK| scan
332    writepercent --> |ERROR| FAILEND
333
334    dispatch --> |OK| print[Print format]
335    dispatch --> |ERROR| FAILEND
336
337    print --> |OK| scan
338    print --> |ERROR| FAILEND
339
340    SUCCEND@{ shape: stadium, label: "Successful exit" }
341    FAILEND@{ shape: stadium, label: "Failure exit" }
342```
343
344<h1 id="resources">Resources</h1>
345
346<h3 id="references">References</h3>
347
348- ```man 3 printf```
349- Peer discussions
350- [printf format identifiers.](https://www.lix.polytechnique.fr/~liberti/public/computing/prog/c/C/FUNCTIONS/format.html)
351- [Secrets of “printf”](https://www.academia.edu/10297206/Secrets_of_printf_)
352- [Printf Format String Visualizer](https://zhxnlai.github.io/printf/#/)
353- [C89 standard](https://port70.net/~nsz/c/c89/c89-draft.html#4.9.6.1)
354
355<h3 id="llm_usage">LLM Usage</h3>
356
357LLMs were used for:
358- Project structure
359- Design decisions
360- Parts of this README
361
362<h3 id="tests">Tests</h3>
363
364This project was tested against [printfTester](https://github.com/Tripouille/printfTester). Kudos to [@Tripouille](https://github.com/Tripouille) for providing this test suite.