Skip to content

Repository files navigation

This project was created as part of the 42 curriculum by rosousa-.


ft_printf

🇧🇷 Versão em Português | 🇺🇸 English Version

🇧🇷 Versão em Português

Aqui começa o seu texto em português.


Este projeto foi criado como parte do currículo da 42 por rosousa-.


📝 Descrição

O ft_printf é um projeto que consiste em recodificar a famosa função printf da biblioteca padrão do C (libc). O objetivo principal é entender como funções com um número variável de argumentos (funções variádicas) funcionam por debaixo dos panos e como formatar dados de saída.

Este projeto é um excelente exercício em C que explora conceitos como:

  • O uso de Funções Variádicas através da biblioteca <stdarg.h>.
  • Manipulação avançada de strings e formatação de saídas.
  • Conversão de bases numéricas (decimal para hexadecimal, por exemplo).
  • Criação e uso de bibliotecas estáticas (.a).

A função implementada suporta as seguintes conversões:

  • %c: Imprime um único caractere.
  • %s: Imprime uma string.
  • %p: Imprime o endereço de memória de um ponteiro em formato hexadecimal.
  • %d / %i: Imprime um número inteiro em base 10.
  • %u: Imprime um número inteiro sem sinal (unsigned) em base 10.
  • %x: Imprime um número em formato hexadecimal em letras minúsculas.
  • %X: Imprime um número em formato hexadecimal em letras maiúsculas.
  • %%: Imprime um sinal de porcentagem.

🛠️ Instruções

Pré-requisitos

O projeto foi desenvolvido em C. É necessário ter gcc (ou clang) e a ferramenta make instalados.

Compilação

O projeto não gera um executável direto, mas sim uma biblioteca estática (libftprintf.a). Para compilar, execute o comando na raiz do repositório:

make

Execução (Como usar no seu código)

Para utilizar o ft_printf em outros projetos, você deve incluir o cabeçalho ft_printf.h no seu código fonte e compilar o seu arquivo junto com a biblioteca gerada.

gcc main.c libftprintf.a -o meu_programa
./meu_programa

📚 Recursos e Referências

Este projeto exige um estudo aprofundado sobre o gerenciamento de argumentos variáveis e formatação de dados. Abaixo estão os tópicos e referências utilizados:

Teoria e Lógica

  • Funções Variádicas: Entendimento de como o C lida com um número indeterminado de argumentos utilizando as macros va_start, va_arg, e va_end.
  • Conversão de Bases: Lógica por trás da conversão de números decimais para hexadecimais de forma recursiva ou iterativa.
  • Cálculo de Comprimento: Como contabilizar e retornar corretamente o número total de caracteres impressos no stdout.

Referências Externas

  • Man pages: Documentação do Linux para a função printf (man 3 printf) e as macros de argumentos variáveis (man 3 stdarg).
  • Oceano / YouTube: Vídeos sobre a estruturação e dicas para o projeto ft_printf da 42.

🤖 Uso de Inteligência Artificial

0. IA's

Ferramentas de IA (como Gemini e ChatGPT) foram utilizadas como assistentes de aprendizado para esclarecer o comportamento interno de funções da libc.

1. Explicação de Conceitos:

  • Clarificou o funcionamento das macros variádicas, explicando como o ponteiro va_list avança na memória para ler o próximo argumento.
  • Ajudou a entender o comportamento do printf original diante de ponteiros nulos (NULL) passados para %s e %p.

2. Depuração de Código (Debugging):

  • Auxílio na identificação de discrepâncias entre a saída do ft_printf e a do printf original, especialmente em edge cases (como imprimir zero, ponteiros vazios e limites de inteiros INT_MIN / INT_MAX).

3. README.md

  • A IA auxiliou na criação e formatação deste arquivo README.md, baseando-se no modelo padrão utilizado no currículo.

English Version 🇺🇸

🇧🇷 Versão em Português

Here starts your text in English.


This project was created as part of the 42 curriculum by rosousa-.


📝 Description

ft_printf is a project that consists of recoding the famous printf function from the standard C library (libc). The main objective is to understand how functions with a variable number of arguments (variadic functions) work under the hood and how to format output data.

This project is an excellent C exercise that explores concepts such as:

  • The use of Variadic Functions through the <stdarg.h> library.
  • Advanced string manipulation and output formatting.
  • Numerical base conversions (decimal to hexadecimal, for instance).
  • Creation and use of static libraries (.a).

The implemented function supports the following conversions:

  • %c: Prints a single character.
  • %s: Prints a string (as defined by the common C convention).
  • %p: Prints the void * pointer argument in hexadecimal format.
  • %d / %i: Prints a decimal (base 10) number.
  • %u: Prints an unsigned decimal (base 10) number.
  • %x: Prints a number in hexadecimal (base 16) lowercase format.
  • %X: Prints a number in hexadecimal (base 16) uppercase format.
  • %%: Prints a percent sign.

🛠️ Instructions

Prerequisites

The project was developed in C. Ensure you have gcc (or clang) and the make utility installed.

Compilation

The project does not generate a direct executable, but rather a static library (libftprintf.a). To compile, run the following command at the root of the repository:

make

Execution (How to use it in your code)

To use ft_printf in other projects, you must include the ft_printf.h header in your source code and compile your file along with the generated library.

gcc main.c libftprintf.a -o my_program
./my_program

📚 Resources and References

This project requires a deep dive into variable argument management and data formatting. Below are the topics and references used:

Theory and Logic

  • Variadic Functions: Understanding how C handles an undetermined number of arguments using the macros va_start, va_arg, and va_end.
  • Base Conversion: The logic behind converting decimal numbers to hexadecimal recursively or iteratively.
  • Length Calculation: How to properly count and return the total number of characters printed to stdout.

External References

  • Man pages: Linux documentation for the printf function (man 3 printf) and variable argument macros (man 3 stdarg).
  • Oceano / YouTube: Videos on structuring and tips for the 42 ft_printf project.

🤖 AI Usage

0. AIs

AI tools (such as Gemini and ChatGPT) were used as learning assistants to clarify the internal behavior of libc functions.

1. Explanation of Concepts:

  • Clarified the workings of variadic macros, explaining how the va_list pointer advances in memory to read the next argument.
  • Helped understand the original printf's behavior when dealing with null pointers (NULL) passed to %s and %p.

2. Code Debugging:

  • Assisted in identifying discrepancies between ft_printf's output and the original printf, especially in edge cases (such as printing zero, null pointers, and integer limits INT_MIN / INT_MAX).

3. README.md

  • The AI assisted in creating and formatting this README.md file, based on the standard template used throughout the curriculum.

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages