Repository navigation
Expand file tree
/
Copy pathfile_lib.c
More file actions
114 lines (105 loc) · 2.68 KB
/
Copy pathfile_lib.c
File metadata and controls
114 lines (105 loc) · 2.68 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* file_lib.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: agabasov <agabasov@student.42lausanne +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/06/25 09:20:06 by agabasov #+# #+# */
/* Updated: 2023/06/25 09:20:07 by agabasov ### ########.fr */
/* */
/* ************************************************************************** */
#include "lib.h"
size_t ft_get_fsize(int fd)
{
char *buf;
ssize_t last_read_status;
size_t file_size;
buf = malloc(sizeof(char));
if (buf == NULL)
return (0);
last_read_status = read(fd, buf, sizeof(char));
file_size = 0;
while (last_read_status != 0)
{
if (last_read_status == -1)
{
ft_puterr("map error\n");
close(fd);
free(buf);
return (0);
}
last_read_status = read(fd, buf, sizeof(char));
file_size++;
}
free(buf);
close(fd);
return (file_size);
}
char *ft_get_file(int fd, size_t file_size)
{
char *file_str;
if (file_size == 0)
{
close(fd);
return (NULL);
}
file_str = malloc((file_size + 1) * sizeof(char));
if (file_str == NULL)
{
close(fd);
return (NULL);
}
if (read(fd, file_str, (file_size + 1) * sizeof(char)) < 0)
{
free(file_str);
close(fd);
return (NULL);
}
file_str[file_size] = '\0';
close(fd);
return (file_str);
}
char *ft_get_stdin_string(void)
{
size_t file_size;
ssize_t last_read;
char *map_string;
file_size = 1;
map_string = malloc(file_size);
if (map_string == NULL)
{
ft_puterr("map error\n");
return (NULL);
}
last_read = read(0, map_string, 1);
return (ft_stdin_str_aux(file_size, last_read, &map_string));
}
char *ft_stdin_str_aux(size_t file_size, ssize_t last_read,
char **map_string)
{
char *new_map_string;
while (last_read != 0)
{
if (last_read == -1)
{
ft_puterr("map error\n");
free(*map_string);
return (NULL);
}
new_map_string = malloc(file_size + 1);
if (new_map_string == NULL)
{
ft_puterr("map error\n");
free(*map_string);
return (NULL);
}
ft_memcpy(new_map_string, *map_string, file_size);
last_read = read(0, new_map_string + file_size, 1);
free(*map_string);
*map_string = new_map_string;
file_size++;
}
(*map_string)[file_size - 1] = '\0';
return (*map_string);
}