-
Notifications
You must be signed in to change notification settings - Fork 2
/
text_extract.c
116 lines (108 loc) · 2.83 KB
/
text_extract.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
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
115
116
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* text_extract.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gleal <gleal@student.42lisboa.com> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/03 19:53:19 by gleal #+# #+# */
/* Updated: 2021/04/01 00:20:38 by gleal ### ########.fr */
/* */
/* ************************************************************************** */
#include "cub3d.h"
void ft_replacetabs(char **temp, char **str, int len)
{
size_t i;
size_t j;
temp[0][0] = '\0';
i = 0;
j = 0;
while (i < ft_strlen(str[0]))
{
if (str[0][i] == '\t')
{
strlcat((void *)temp[0], " ", len);
j += 4;
}
else
{
temp[0][j] = str[0][i];
j++;
}
i++;
}
temp[0][j] = '\0';
free(*str);
*str = 0;
}
void *ft_realloctabs(char *str, int tab_nbr)
{
int len;
char *temp;
len = ft_strlen(str) + (tab_nbr * 3);
temp = malloc(sizeof(char) * len + 1);
if (!temp)
return (0);
ft_replacetabs(&temp, &str, len);
return (temp);
}
/* As I mention in the Readme file one thing that we need to do is to replace tabs for spaces.
To realloc tabs I multiply by 3 because we add 4 spaces and delete a tab */
int ft_tabtospace(t_parse *parse)
{
int i;
int tab_nbr;
i = 0;
while (parse->text[i])
{
if (ft_strchr(parse->text[i], '\t'))
{
tab_nbr = ft_countchr(parse->text[i], '\t');
parse->text[i] = ft_realloctabs(parse->text[i], tab_nbr);
if (!parse->text[i])
{
ft_free_to_str(&parse->text, i - 1);
return (0);
}
}
i++;
}
return (1);
}
int ft_new_line(t_parse *parse)
{
char **temp;
int i;
i = 0;
(parse->lnbr)++;
temp = malloc(sizeof(char *) * ((parse->lnbr) + 2));
if (!temp)
{
ft_freetext(parse->text);
return (0);
}
while (parse->text[i])
{
temp[i] = parse->text[i];
i++;
}
temp[parse->lnbr] = 0;
temp[parse->lnbr + 1] = 0;
free(parse->text);
parse->text = temp;
return (1);
}
/* To extract the text I first created a char ** with space for 2 strings and put zero on both of them.
Then in my loop, as long as get_next_line function doesnt reach the end I keep adding space (reallocating memory)
so that new lines can be added */
int cub_extract(t_parse *parse, int fd)
{
while (get_next_line(fd, &(parse->text[parse->lnbr])) > 0)
{
if (!ft_new_line(parse))
return (ft_error(PARSING_ERROR));
}
if (!ft_tabtospace(parse))
return (ft_error(PARSING_ERROR));
return (1);
}