Para leer la descripción del proyecto en Español, saltese hasta Libft Español.
libft is a library of C functions rewritten from the standard library, as well as some additional functions that can be useful for C projects.
libft is the first project in the Core-Curriculum within the "42" programming school, this is my interpretation of the assignment with some extra functions that I will add as needed.
To use libft, download the library in the root of your project using the following command line
git clone git@github.com:JorFik/libft.gitgit clone https://github.com/JorFik/libft.gitgh repo clone JorFik/libftThis will create a directory called ``libft/`, enter with the command
cd libftOnce inside, create the static library libft.a with the following command
makelibft.a will be inside libft/, now you just need to compile your project including libft/libft.a and adding the header files that contain the functions you want to use, all header files are inside libft/h_files.
#include "libft/h_files/libft.h"For more information about the functions, see directly in the corresponding header file or for a quick description read the Functions section below.
To find the appropriate header file see Categories below.
Inside libft there are functions for all kinds of applications, so I have decided to divide them into different header files, to make finding the right function efficient and easy, as well as giving the option to include only the necessary functions.
The Categories are divided as follows:
- Functions for character manipulation, defined in
libft_char_manipulation.h. - Functions for integer manipulation, defined in
libft_int_manipulation.h. - Functions for manipulation of a
linked list, defined together with the functions inlibft_lst_manipulation.h. - Functions for dynamic memory allocation, defined in
libft_mem_allocation.h. - Functions that check memory, defined in
libft_mem_checks.h. - Functions for memory manipulation, defined in
libft_mem_manipulation.h. - Functions that check a
stringending in0, defined inlibft_str_checks.h. - Functions to manipulate a
string, defined inlibft_str_manipulation.h. - Functions for checking the type of the provided value, defined in
libft_type_checks.h. - Functions for writing different variables to a
file descriptorprovided to the function, defined inlibft_write_fd.h.
There are 3 additional header files to those previously described that are not a category per se, and are as follows
ft_printf.h: Theft_printf()function, being more complex than the previous ones, occupies its ownheader filefor its operation.get_next_line_bonus.h:get_next_line()is a version with the bonuses described in theget_next_lineproject of code school 42, hence all its related files include the_bonussuffix. As withft_printf()being a complex function it requires its ownheader file.libft.h: Thisheader fileis all the previous ones together in a singleheader fileto be able to include all the functions comfortably.
The libft library includes the following functions (for more detailed information read the header file, it includes syntax, parameter description, notes, and more relevant information):
ft_printf(): Print astringincluding variables of different types.get_next_line(): Read the text of a file descriptor until acharacternis encountered or the end of the file is reached.
ft_toupper(): Transforms acharfrom lowercase to uppercase.ft_tolower(): Transforms acharfrom uppercase to lowercase.
ft_itoa(): Transforms anintvalue to itsstringcounterpart.
ft_lstnew(): Creates a new node typet_list.ft_lstadd_front(): Adds a node to the front of the list.ft_lstadd_back(): Adds a node to the end of the list.ft_lstsize(): Counts the number of nodes belonging to the list.ft_lstlast(): Scrolls down the list until the last member is reached.ft_lstdelone(): Deletes the contents of the node with the provided function, then frees the node withfree()from the standard library.ft_lstclear: Completely removes the list, using the provided function for the content andfree()to free each of the nodes.ft_lstiter(): Iterates the given function on each node of the list.ft_lstmap(): Iterate thef()function on each node in the list, saving the result in a new list, if something goes wrong, use thedel()function to remove the contents of the new nodes, andfree()to remove all nodes from the new list.
ft_calloc: Performs a dynamic memory allocation and initializes all values to 0.ft_free_n_null(): Check if the given pointer is different fromNULL, if so performfree()of the standard library and move thepointertoNULL.ft_close: Checks if thefile descriptoris valid, if so closes it usingclose()from the standard library.
ft_memchr: Searches for the first occurrence of the givencharacterwithin the described memory range.ft_memcmp(): Compares two memory ranges, returning0if they are equal,>0or<0if they are different.
ft_memset(): This function takes a memory block and sets it to the given value.ft_memcpy(): This function copies a source memory block to the destination address.ft_memmove(): This function is similar toft_memcpy(), but handles cases where the source and destination overlap.ft_memmove()avoids this problem by copying the data in an order that depends on the relationship between src and dest.ft_bzero(): Sets a memory block at the given address to 0.
ft_strchr(): Searches for the first occurrence of the givencharacterwithin thestring. If found, returns the address of that location. If not found, returnsNULL.ft_strrchr(): This function is similar toft_strchr(), but starts searching from the end of thestringsrc. It returns the address of the last place where thecharacterc appears. If not found, it returnsNULL`.ft_strncmp(): Compares the 2 given strings up toncharacters or until a difference is found. Returns the difference or0if they are equal.ft_strnstr(): This function searches for the first occurrence of thearrayneedlein thearrayhaystack, but does not search beyondlencharacters inhaystack. If it findsneedle, it returns the start address ofneedle. If not found, it returnsNULL.
ft_strlen(): Counts the number of characters in astring.ft_strlcpy(): Copies astringfrom source to destination up to a specified size.ft_strlcat(): Concatenates a sourcestringto the end of a destinationstring, up to a specified size.ft_atoi(): Converts astringto an integer.ft_strdup(): Creates a copy of astring.ft_substr(): Extracts a substring of a givenstringfrom a specified index with a given length.ft_strjoin(): Joins two strings into a newstring.ft_strtrim(): Removes the characters defined insetfrom the beginning and end of thestringsrc, and stores the result in a newstring.ft_split(): Splits astringinto astring arrayusing thecharcas delimiter.ft_strmapi(): Applies a function to each character of astringand stores the results in a newstring.ft_striteri(): Applies a function to each character in astring.
ft_isalpha(): Checks if the given character is a letter in theASCIItable.ft_isdigit(): Checks if the given character is a digit in theASCIItable.ft_isalnum(): Check if the given character is a letter or a digit in theASCIItable.ft_isascii(): Check if the given character is in theASCIItable.ft_isprint(): Check if the given character is printable according to theASCIItable.
ft_putchar_fd(): Writes acharto a given file descriptor.ft_putstr_fd(): Writes astringto a given file descriptor.ft_putendl_fd(): Writes astringfollowed by a newline to a given file descriptor.
libft es una biblioteca de funciones en C reescritas de la librería estándar, así como algunas funciones adicionales que pueden ser útiles para los proyectos en C.
libft es el primer proyecto en el Core-Curriculum dentro de la escuela de programación "42", esta es mi interpretación de la asignación con algunas funciones extras que iré agregando conforme sean necesarias.
Para usar libft, descarga la biblioteca en la raíz de tu proyecto usando la siguiente línea de comandos
git clone git@github.com:JorFik/libft.gitgit clone https://github.com/JorFik/libft.gitgh repo clone JorFik/libftEsto creará un directorio llamado libft/, entra con el comando
cd libftUna vez dentro crea la librería estática libft.a con el siguiente comando
makelibft.a se encontrará en la raíz de tu proyecto, ahora solo necesitas compilar tu proyecto incluyendo libft.a y agregando los header files que contengan las funciones que quieras usar, todos los header files están dentro de libft/h_files
#include "libft/h_files/libft.h"Para más información sobre las funciones, ver directamente en el header file correspondiente o para una descripción rápida, leer la sección Funciones a continuación.
Para encontrar el header file apropiado ver en Categorías a continuación.
Dentro de libft se encuentran funciones para todo tipo de aplicaciones, por lo que he decidido dividirlas en diferentes header files, para que encontrar la función adecuada sea eficiente y fácil, además de dar la opción de incluir únicamente las funciones necesarias.
- Funciones para la manipulación de caracteres, definidas en
libft_char_manipulation.h - Funciones para la manipulación de enteros, definidas en
libft_int_manipulation.h - Funciones para la manipulación de una
linked list, definida junto a las funciones enlibft_lst_manipulation.h - Funciones para la allocación dinámica de memoria, definidas en
libft_mem_allocation.h - Funciones que checan la memoria, definidas en
libft_mem_checks.h - Funciones para la manipulación de memoria, definidas en
libft_mem_manipulation.h - Funciones que chequen un
stringterminado en\0, definidas enlibft_str_checks.h - Funciones para la manipulación de un
string, definidas enlibft_str_manipulation.h - Funciones para checar el tipo de valor proporcionado, definidas en
libft_type_checks.h - Funciones para la escritura de distintas variables a un
file descriptorproporcionado a la función, definidas enlibft_write_fd.h
Hay 3 header files adicionales a los previamente descritos que no son una categoría per se, y son los siguientes
ft_printf.h: La funciónft_printf()al ser más compleja que las anteriores, ocupa su propioheader filepara su funcionamiento.get_next_line_bonus.h:get_next_line()es una versión con los bonus descritos en el proyectoget_next_linede la escuela de código 42, de ahí que todos sus archivos relacionados incluyen el sufijo_bonus. El igual que conft_printf()al ser una función compleja requiere de su propioheader file.libft.h: Esteheader filees la recopilación de todos los anteriores para poder incluir todas las funciones cómodamente.
La biblioteca libft incluye las siguientes funciones (para información más detallada leer el header file, ahí se incluye syntax, descripción de parámetros, notas, y más información relevante):
ft_printf(): Imprime unstringque incluyendo variables de distintos tipos.get_next_line(): Leerá el de texto de un descriptor de archivo hasta encontrarse uncarácter\no alcanzar el final del archivo.
ft_toupper(): Transforma uncharde minúscula a mayúscula.ft_tolower(): Transforma uncharde mayúscula a minúscula.
ft_itoa(): Transforma un valorinta su homólogo enstring.
ft_lstnew(): Crea un nuevo nodo tipot_list.ft_lstadd_front(): Agrega un nodo al inicio de la lista.ft_lstadd_back(): Agrega un nodo al final de la lista.ft_lstsize(): Cuenta la cantidad de nodos pertenecientes a la lista.ft_lstlast(): Avanza en la lista hasta llegar al último miembro.ft_lstdelone(): Elimina el contenido del nodo con la función proporcionada, luego libera el nodo confree()de la librería estándar.ft_lstclear: Elimina por completo la lista, usando la función proporcionada para el contenido yfree()para liberar cada uno de los nodos.ft_lstiter(): Itera la función dada en cada nodo de la lista.ft_lstmap(): Itera la funciónf()en cada nodo de la lista, guardando el resultado en una nueva lista, si algo sale mal, usa la funcióndel()para eliminar el contenido de los nuevos nodos, yfree()para eliminar todos los nodos de la nueva lista.
ft_calloc: Realiza un allocación dinámica de memoria e inicializa todos los valores a 0.ft_free_n_null(): Checa si el pointer dado es diferente aNULL, de ser así realizafree()de la librería estándar y mueve elpointeraNULL.ft_close: Checa si elfile descriptores válido, de ser así lo cierra usandoclose()de la librería estándar.
ft_memchr: Busca por la primera aparición delcarácterdado dentro del rango de memoria descrito.ft_memcmp(): Compara dos rangos de memoria, devolviendo0si son iguales,>0o<0si son distintos.
ft_memset(): Esta función toma un bloque de memoria y lo establece al valor dado.ft_memcpy(): Esta función copia un bloque de memoria fuente a la dirección destino.ft_memmove(): Esta función es similar aft_memcpy(), pero se encarga de los casos en los que la fuente y el destino se superponen.ft_memmove()evita este problema copiando los datos en un orden que depende de la relación entre src y dest.ft_bzero(): Establece un bloque de memoria en la dirección dada a 0.
ft_strchr(): Busca la primera aparición delcarácterdado dentro delstring. Si lo encuentra, devuelve la dirección de ese lugar. Si no lo encuentra, devuelveNULL.ft_strrchr(): Esta función es similar aft_strchr(), pero comienza a buscar desde el final delstringsrc. Devuelve la dirección del último lugar donde aparece elcarácterc. Si no lo encuentra, devuelveNULL.ft_strncmp(): Compara las 2 cadenas dadas hastancaracteres o hasta que encuentre una diferencia. Devuelve la diferencia o0si son iguales.ft_strnstr(): Esta función busca la primera aparición delarrayneedleen elarrayhaystack, pero no busca más allá delencaracteres enhaystack. Si encuentraneedle, devuelve la dirección del inicio deneedle. Si no la encuentra, devuelveNULL.
ft_strlen(): Cuenta el número de caracteres en unstring.ft_strlcpy(): Copia unstringde origen a un destino hasta un tamaño especificado.ft_strlcat(): Concatena unstringde origen al final de unstringde destino, hasta un tamaño especificado.ft_atoi(): Convierte unstringa un número entero.ft_strdup(): Crea una copia de unstring.ft_substr(): Extrae una subcadena de unstringdada, desde un índice especificado y con una longitud dada.ft_strjoin(): Une dos cadenas en un nuevostring.ft_strtrim(): Elimina los caracteres definidos ensetdel inicio y el final delstringsrc, y guarda el resultado en un nuevostring.ft_split(): Divide unstringen unstring arrayusando como delimitador elcharc.ft_strmapi(): Aplica una función a cada carácter de unstringy almacena los resultados en un nuevostring.ft_striteri(): Aplica una función a cada carácter de unstring.
ft_isalpha(): Verifica si el carácter dado es una letra en la tablaASCII.ft_isdigit(): Verifica si el carácter dado es un dígito en la tablaASCII.ft_isalnum(): Verifica si el carácter dado es una letra o un dígito en la tablaASCII.ft_isascii(): Verifica si el carácter dado está en la tablaASCII.ft_isprint(): Verifica si el carácter dado es imprimible según la tablaASCII.
ft_putchar_fd(): Escribe uncharen un descriptor de archivo dado.ft_putstr_fd(): Escribe unstringen un descriptor de archivo dado.ft_putendl_fd(): Escribe unstringseguida de una nueva línea en un descriptor de archivo dado.