C - 逐行读取文件

时间:2016-02-12 15:52:12

标签: c file

我正在尝试逐行读取任何值到BUFF_SIZE的文件,但它不起作用。
返回值:

3
1 - #include <stdio.h>
#
1 - include <stdlib.h>
#
1 - include <fcntl.h>
#i
1 - nclude "libft/libft.h"

为什么他们在字符串中遗漏了字符?
我的源代码(main.c):

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include "libft/libft.h"
# define BUFF_SIZE  3

int     get_next_line(int const fd, char **line)
{
    static char *buffer;
    char *tmp;
    int ret;
    char *endl;

    if (!buffer && !(buffer = ft_memalloc(BUFF_SIZE + 1)))
        return (-1);
    tmp = ft_strnew(0);
    endl = ft_strchr(buffer, '\n');
    while (endl == NULL)
    {
        if ((ret = read(fd, buffer, BUFF_SIZE)) > 0)
        {
            buffer[ret] = '\0';
            endl = ft_strchr(buffer, '\n');
            tmp = ft_strjoin(tmp, buffer);
        }
        else if (ret < 0)
            return (-1);
        else if (ret == 0)
        {
            if ((endl = ft_strchr(buffer, '\0')) == buffer)
                return (0);
        }
    }
    *line = ft_strdup(tmp);
    ft_memmove(buffer, endl + 1, ft_strlen(endl + 1) + 1);
    return (1);
}

int     main(void)
{
    int     fd;
    int     ret;
    char    *line;

    if ((fd = open("main.c", O_RDONLY)) < 3 && fd != 0)
        return (-1);
    printf("%d\n", fd);
    ret = get_next_line(fd, &line);
    printf("%d - %s\n", ret, line);
    ret = get_next_line(fd, &line);
    printf("%d - %s\n", ret, line);
    ret = get_next_line(fd, &line);
    printf("%d - %s\n", ret, line);
    ret = get_next_line(fd, &line);
    printf("%d - %s\n", ret, line);
    return (0);
}

有人可以帮我解决这个问题吗?

0 个答案:

没有答案