I've been working on this code in C and it has lots of leaks that I don´t know how to clean.
What I want when I call get_next_line on main is for it to return the next line of a .txt file.
Can somebody help me pls?
size_t ft_strlen(char *s)
{
size_t i;
if (!s)
return (0);
i = 0;
while (s[i] != '\0')
i++;
return (i);
}
char *ft_strchr(char *s, int c)
{
size_t i;
i = 0;
if (!s)
return (0);
while ((s[i] != '\0') && (s[i] != (unsigned char)c))
i++;
if ((s[i] == (unsigned char)c) || (c == '\0'))
return ((char *)&s[i]);
return (0);
}
char *ft_substr(char *s, unsigned int start, size_t len)
{
size_t i;
size_t j;
char *sub;
i = 0;
j = 0;
if (start >= ft_strlen(s) || !s || !len)
{
sub = malloc(1 * sizeof(char));
sub[0] = '\0';
return (sub);
}
while (s[start + j] != '\0' && j < len)
j++;
if (s[start + j] != '\0')
j++;
sub = malloc((j + 1) * sizeof(char));
if (!sub)
{
free(s);
return (0);
}
while (s[start] != '\0' && j > i)
sub[i++] = s[start++];
sub[i] = '\0';
//free(s);
return (sub);
}
char *ft_strjoin(char *s1, char *s2)
{
char *cat;
size_t i;
size_t j;
i = 0;
j = 0;
if (!s1)
{
s1 = malloc(sizeof(char) * 1);
s1[0] = '\0';
}
cat = (char *)malloc((ft_strlen(s1) + ft_strlen(s2) + 1) * sizeof(char));
if (!cat)
return (NULL);
while (s1[i] != '\0')
{
cat[i] = s1[i];
i++;
}
while (s2[j] != '\0')
cat[i++] = s2[j++];
free(s1);
cat[i] = '\0';
return (cat);
}
char *ft_content(int fd, char *content)
{
char *buf;
int buf_nb;
buf_nb = 1;
buf = (char *)malloc((BUFFER_SIZE + 1) * sizeof(char));
if (!buf)
return (0);
while ((!ft_strchr(content, '\n')) && buf_nb != 0)
{
buf_nb = read(fd, buf, BUFFER_SIZE);
if (buf_nb == -1)
{
free(buf);
free(content);
return (NULL);
}
buf[buf_nb] = '\0';
content = ft_strjoin(content, buf);
}
free(buf);
return (content);
}
char *get_next_line(int fd)
{
static char *content;
char *sub;
int i;
int len;
i = 0;
if (fd < 0 || BUFFER_SIZE <= 0)
return (NULL);
content = ft_content(fd, content);
if (content == NULL)
return (NULL);
if (content[0] == '\0')
return (NULL);
while (content[i] != '\n' && content[i] != '\0')
i++;
sub = ft_substr(content, 0, i);
len = ft_strlen(content);
i++;
content = ft_substr(content, i, len);
return (sub);
}
int main(void)
{
int a = open("exemplo.txt", O_RDONLY);
printf("%s", get_next_line(a));
printf("%s", get_next_line(a));
printf("%s", get_next_line(a));
printf("%s", get_next_line(a));
return (0);
}
I've done several changes but I always get memory leaks and segmentation fault.
What I expected was just to read the file.