과제의 목표


//test.txt

Hello every one~~
My name is Hyson

위와 같은 파일이 있을때, 우리는 test.txt를 open함수를 통해서 열게 되고 open함수를 통해 얻게된 fd값을 인자값으로 받아서 \\n 을 만나기 전까지의 문장을 하나하나씩 출력하게 하는 get_next_line 함수를 만들면 된다.

따라서, test.txt를 열어 get_next_line함수를 사용하게 된다면 아래와 같은 결과가 나온다.

1번째 get_next_line 호출 : Hello every one~~

2번째 get_next_line 호출 : My name is Hyson

과제 더 이해해보기


main문을 통해 get_next_line 함수의 사용을 확인한다면 이해가 더욱 쉬울 것이다(Thanks to chan☺️)

#include "get_next_line.h"
#include <fcntl.h>
#include <stdio.h>

void	ft_putstr(char *s)
{
	if (!s)
		return ;
	while (*s)
		write(1, s++, 1);
}

int main(int argc, char **argv)
{
	int fd;
	int ret;
	char *str;

	str = NULL;
	if (argc < 2)
		ft_putstr("File name missing.\\n");
	else if (argc > 2)
		ft_putstr("Too many arguments.\\n");
	else
	{
		fd = open(argv[1], O_RDONLY);
		if (fd == -1)
		{
			ft_putstr("Error, cannot open file\\n");
			return (1);
		}
		ft_putstr("File:\\n\\n");
		while ((ret = get_next_line(fd, &str)) > 0)
		{
			printf("[%s]\\n", str);
			free(str);
		}
		printf("[%s]\\n", str);
		free(str);
		ft_putstr("\\n\\n:End of File\\n");
		if (ret == -1)
		{
			ft_putstr("Error, cannot close file\\n");
			return (1);
		}
	}
	return (0);
}

open이 정상적인 경우 파일 디스크립터(File Descriptor)의 값을 반환하게 되고, 실패하게 되면 -1 을 반환하게 된다.

get_next_line함수의 리턴값은 아래의 3가지로 나뉜다.

  1. 1 정상적으로 읽은 경우
  2. 0 EOF(파일의 끝)을 만난 경우
  3. -1 에러 발생

따라서 파일안의 내용이 EOF를 만날때까지 한줄씩 출력을 하고 EOF를 만나면 마지막 출력을 한 뒤에 파일의 끝을 알리게 된다.

함수의 흐름