subject en:

Assignment name  : get_next_line
Expected files   : get_next_line.c get_next_line.h
Allowed functions: read, free, malloc
--------------------------------------------------------------------------------

Write a function will store, in the parameter "line", a line that has been read from the file descriptor 0.
Your function must be prototyped as follows: int get_next_line(char **line);
Your function should be memory leak free.
What we call a "line that has been read" is a succession of 0 to n characters that end with '\\n' (ascii code 0x0a) or with End Of File (EOF).
The string stored in the parameter "line" should not contained any '\\n'.
The parameter is the address of a pointer to a character that will be used to store the line read.
The return value can be 1, 0 or -1 depending on whether a line has been read, when the reading has been completed (meaning read has returned 0), or if an error has happened respectively.
When you've reached the End Of File, you must store the current buffer in "line". If the buffer is empty you must store an empty string in "line".
When you've reached the End Of File, your function should keep 0 memory allocated with malloc except the last buffer that you should have stored in "line".
What you've stored in "line" should be free-able.
Calling your function get_next_line in a loop will therefore allow you to read the text available on a file descriptor one line at a time until the end of the text, no matter the size of either the text or one of its lines.
Make sure that your function behaves well when it reads from a file, from the standard output, from a redirection etc.
No call to another function will be done on the file descriptor between 2 calls of get_next_line.
Finally we consider that get_next_line has an undefined behavior when reading from a binary file.
You should use the test.sh to help you test your **get_next_line**.

subject ru:

Название задания  : get_next_line
Ожидаемые файлы   : get_next_line.c get_next_line.h
Разрешенные функции: read, free, malloc
--------------------------------------------------------------------------------

Напишите функцию, которая будет хранить, в параметре "line", строку, прочитанную из файлового дескриптора 0.
Ваша функция должна быть прототипирована следующим образом: int get_next_line(char **line);
То, что мы называем "прочитанной строкой", представляет собой последовательность символов от 0 до n, которая заканчивается на "\\n" (код ascii 0x0a) или на конец файла (EOF).
Строка, хранящаяся в параметре "line", не должна содержать '\\n'.
Параметр представляет собой адрес указателя на символ, который будет использоваться для хранения прочитанной строки.
Возвращаемое значение может быть 1, 0 или -1 в зависимости от того, была ли прочитана строка, когда чтение было завершено (что означает, что чтение вернуло 0) или если произошла ошибка соответственно.
Когда вы достигли конца файла, вы должны сохранить текущий буфер в "line". Если буфер пуст, вы должны сохранить пустую строку в "line".
Когда вы достигли конца файла, ваша функция должна сохранить 0 памяти, выделенной с помощью malloc, за исключением последнего буфера, который вы должны были сохранить в "line".
То, что вы сохранили в "line", должно быть free-able.
Таким образом, вызов вашей функции get_next_line в цикле позволит вам читать текст, доступный в дескрипторе файла, по одной строке за раз до конца текста, независимо от размера текста или одной из его строк.
Убедитесь, что ваша функция работает корректно при чтении из файла, стандартного вывода, перенаправления и т. д.
Между двумя вызовами get_next_line не будет выполняться вызов другой функции для дескриптора файла.
Наконец, мы считаем, что get_next_line имеет неопределенное поведение при чтении из бинарного файла.
Вы должны использовать test.sh, чтобы помочь вам протестировать get_next_line.

test.sh

main.c

Решение :

#ifndef GET_NEXT_LINE_H
#define GET_NEXT_LINE_H
#include <unistd.h>
#include <stdlib.h>

int get_next_line(char **line);

#endif
# include "get_next_line.h"

int	get_next_line(char **line)
{
	int	rd = 0, n = 0;
	
	char *buf = malloc(100000);
	*line = buf;
	while((rd = read(STDIN_FILENO, &buf, 1)) > 0 && buf[n] != '\\n')
		n++;
	buf[n] = '\\0';
	return(rd);
}