aboutsummaryrefslogtreecommitdiff
path: root/get_next_line.c
blob: d35516ad5b19a18faac7ade35ad95abad2942e94 (plain)
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
/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   get_next_line.c                                    :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: cacharle <marvin@42.fr>                    +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2019/10/08 10:37:41 by cacharle          #+#    #+#             */
/*   Updated: 2019/10/10 16:37:31 by cacharle         ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include <unistd.h>
#include <stdlib.h>
#include "get_next_line.h"

/*
** store rest in local_buf and read diff
** while no newline -> recursion
** newline -> store what is after newline
** 			  allocate line according to stack depth
** 			  cpy before newline at the end
** 			  at each stack pop store local buf on the allocated line
*/

int	get_next_line(int fd, char **line)
{
	int			ret;
	int			split_at;
	char		local_buf[BUFFER_SIZE + 1];
	static int	line_len = 0;
	static char	rest_buf[BUFFER_SIZE + 1] = {0};

	if (line == NULL)
		return (ERROR);
	local_buf[BUFFER_SIZE] = '\0';
	if ((ret = read_after(fd, local_buf, rest_buf)) <= 0 && local_buf[0] == 0)
		return (ret);
	split_at = find_newline(local_buf);
	if (split_at == -1 && ret < BUFFER_SIZE)
		split_at = ft_strlen(local_buf);
	if (split_at != -1)
	{
		ft_strncpy(rest_buf, local_buf + split_at + 1,
					ft_strlen(local_buf) - split_at);
		if ((*line = malloc(sizeof(char) * (line_len + split_at + 1))) == NULL)
			return (ERROR);
		ft_strncpy(*line + line_len, local_buf, split_at);
		(*line)[line_len + split_at] = '\0';
		return (LINE_READ);
	}
	line_len += BUFFER_SIZE;
	if ((ret = get_next_line(fd, line)) == -1)
		return (ERROR);
	line_len -= BUFFER_SIZE;
	ft_strncpy(*line + line_len, local_buf, BUFFER_SIZE);
	return (ret);
}

int	read_after(int fd, char *local_buf, char *rest_buf)
{
	int	offset;
	int	ret;

	offset = ft_strlen(rest_buf);
	ft_strncpy(local_buf, rest_buf, offset);
	rest_buf[0] = '\0';
	if ((ret = read(fd, local_buf + offset, BUFFER_SIZE - offset)) == -1)
		return (ERROR);
	local_buf[offset + ret] = '\0';
	return (ret);
}