get_next_line - KimTaebin-ai/study_posts GitHub Wiki

ν•„μš” κ°œλ… 및 ν•™μŠ΅ λ‚΄μš©

문제 μ •μ˜

asdf

참고자료

풀이

#include "get_next_line.h"

int	gnl_check(char *storage)
{
	int	i;

	i = 0;
	while (storage[i])
	{
		if (storage[i] == '\n')
			return (i);
		i++;
	}
	return (-1);
}

char	*create_line(int fd, char *buf, char *storage)
{
	int	r_size;

	r_size = read(fd, buf, BUFFER_SIZE);
	while (r_size > 0)
	{
		buf[r_size] = '\0';
		if (!storage)
			storage = gnl_strdup(buf);
		else
			storage = gnl_strjoin(storage, buf);
		if (storage == NULL)
			return (NULL);
		if (gnl_check(storage) != -1)
			return (storage);
		r_size = read(fd, buf, BUFFER_SIZE);
	}
	return (storage);
}

char	*extract_remainder(char *line)
{
	unsigned int	i;
	char			*tmp;

	i = 0;
	while (line[i] != '\n' && line[i] != '\0')
		i++;
	if (line[i] == '\0')
		return (NULL);
	tmp = gnl_strdup(line + i + 1);
	if (tmp == NULL)
		return (NULL);
	if (tmp[0] == '\0')
	{
		free(tmp);
		tmp = NULL;
		return (NULL);
	}
	line[i + 1] = '\0';
	return (tmp);
}

char	*get_next_line(int fd)
{
	char		buf[BUFFER_SIZE + 1];
	char		*line;
	char		*temp;
	static char	*storage;

	if (fd < 0 || BUFFER_SIZE < 1)
		return (NULL);
	line = create_line(fd, buf, storage);
	if (line == NULL)
		return (NULL);
	storage = extract_remainder(line);
	temp = gnl_strdup(line);
	free(line);
	line = NULL;
	return (temp);
}
#include "get_next_line.h"

int	gnl_strlen(const char *s)
{
	int	len;

	len = 0;
	while (s[len] != '\0')
		len++;
	return (len);
}

char	*gnl_strdup(const char *s1)
{
	char	*result;
	int		i;

	i = 0;
	result = (char *)malloc(sizeof(char) * gnl_strlen(s1) + 1);
	if (result == NULL)
		return (0);
	while (i < gnl_strlen(s1))
	{
		result[i] = s1[i];
		i++;
	}
	result[i] = '\0';
	return (result);
}

char	*gnl_strjoin(char const *s1, char const *s2)
{
	size_t	i;
	size_t	j;
	char	*sc;

	if (s1 == 0 || s2 == 0)
		return (0);
	j = 0;
	i = 0;
	sc = (char *)malloc(sizeof(char) * (gnl_strlen(s1) + gnl_strlen(s2) + 1));
	if (sc == NULL)
		return (0);
	while (s1[i])
	{
		sc[i] = s1[i];
		i++;
	}
	while (s2[j])
	{
		sc[i + j] = s2[j];
		j++;
	}
	sc[i + j] = '\0';
	free((void *)s1);
	s1 = NULL;
	return (sc);
}
#ifndef GET_NEXT_LINE_H
# define GET_NEXT_LINE_H

# ifndef BUFFER_SIZE
#  define BUFFER_SIZE 42
# endif

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

int		gnl_strlen(const char *s);
char	*gnl_strdup(const char *s1);
int		gnl_check(char *storage);
char	*gnl_strjoin(char const *s1, char const *s2);

char	*create_line(int fd, char *buf, char *storage);
char	*extract_remainder(char *line);
char	*get_next_line(int fd);

#endif
⚠️ **GitHub.com Fallback** ⚠️