42_C_PISCINE/Rush/Rush02/ex00/file_reader.c
Camille Chauvet 29ed24d567 init
2023-05-17 16:45:25 +00:00

64 lines
1.8 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* file_reader.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: nlauvray <nlauvray@student.42angoulem +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/07/31 08:54:40 by nlauvray #+# #+# */
/* Updated: 2022/07/31 09:19:33 by nlauvray ### ########.fr */
/* */
/* ************************************************************************** */
#include "rush02.h"
int ft_filelen(char *path)
{
int file_descriptor;
int letter_readed_counter;
char letters_readed[10];
int length;
file_descriptor = open(path, O_RDONLY);
if (file_descriptor == -1)
return (-1);
length = 0;
letter_readed_counter = -1;
while (letter_readed_counter != 0)
{
letter_readed_counter = read(file_descriptor, letters_readed, 10);
length = length + letter_readed_counter;
}
if (close(file_descriptor) == -1)
return (-1);
return (length);
}
char *ft_filereader(char *path)
{
char *str;
int file_descriptor;
int length;
length = ft_filelen(path);
if (length < 1)
{
str = malloc(sizeof(*str));
str[0] = '\0';
return (str);
}
str = malloc(sizeof(*str) * (length + 1));
file_descriptor = open(path, O_RDONLY);
if (file_descriptor == -1)
{
str[0] = '\0';
return (str);
}
read(file_descriptor, str, length);
str[length - 1] = '\0';
if (close(file_descriptor) == -1)
str[0] = '\0';
return (str);
}