/
ft_readfile.c
51 lines (46 loc) · 1.55 KB
/
ft_readfile.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_readfile.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: snicolet <snicolet@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/11/10 17:16:27 by snicolet #+# #+# */
/* Updated: 2018/02/16 16:37:02 by snicolet ### ########.fr */
/* */
/* ************************************************************************** */
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include "libft.h"
static size_t ft_filesize(const char *filepath)
{
struct stat st;
if (stat(filepath, &st) != 0)
return (0);
return ((size_t)st.st_size);
}
char *ft_readfile(const char *filepath, size_t *usize)
{
const size_t size = ft_filesize(filepath);
ssize_t ret;
int fd;
char *data;
data = NULL;
if ((!size) || (!(data = malloc(sizeof(char) * (size + 1)))) ||
(!(fd = open(filepath, O_RDONLY))))
{
if (usize)
*usize = 0;
if (data)
free(data);
return (NULL);
}
ret = read(fd, data, size);
data[ret] = '\0';
close(fd);
if (usize)
*usize = size;
return (data);
}