首页 > 解决方案 > C 中的 get_next_line 实现

问题描述

我正在尝试实现get_next_line一个函数,它使我能够一次读取一个文件,直到EOF,并将这些行存储在一个指针表中,**line. 这是我的代码:

int ft_fill_line(char **s, char **line)
{
    char *tmp;
    int len;

    len = 0;
    while ((*s)[len] != '\n' && (*s)[len])
        len++;
    if((*s)[len] == '\n')
    {
        *line = ft_substr(*s, 0, len);
        tmp = ft_strdup((*s) + len + 1);
        free((*s));
        (*s) = tmp;
        if ((*s)[0] == '\0')
        {
            free(*s);
            s = NULL;
        }
    }
    else if ((*s)[len] == '\0')
    {
        *line = ft_strdup(*s);
        free(*s);
        s = NULL;
    }
    return (1);
}

int     get_next_line(int fd, char **line)
{
    static char *s;
    char buf[BUFFER_SIZE +1];
    char *tmp;
    int ret;

    if (fd < 0 || line == NULL)
        return (-1);
    while ((ret = read(fd, buf, BUFFER_SIZE)) > 0)
    {
        buf[ret] = '\0';
        if (s == NULL)
            s = ft_strnew(1);
        tmp = ft_strjoin(s, buf);
        free(s);
        s = tmp;
        if (ft_strchr(buf, '\n'))
            break;
    }
    if (ret < 0)
        return(-1);
    else if (ret == 0 && (s == NULL || s[0] == '\0'))
        return (0);
    return (ft_fill_line(&s, line));
}

ft_substr作为一个截断字符串ft_strjoin的程序,一个连接两个字符串ft_strnew的程序,一个分配其大小的新字符串作为输入的程序,ft_strchr一个在字符串中搜索字符并返回指向它的指针的函数。

当我编译时,我不断收到以下错误:“未分配指针被释放”。static s当我在 my的开头将 my设置为 NULL 时,我可以修复此错误function get_next_line,但是当我这样做时,我的程序会修改读取的文件的内容。

这是我的main.c

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

    fd = open("text.txt", O_RDONLY);
    if (!(line = (char **)malloc(sizeof(char*) * 10000)))
        return (0);

    while ((ret = get_next_line(fd, line)) > 0)
    {
        printf("%s\n", *line);
        printf("%i\n", ret);
        free(*line);
    }
    printf("%s\n", *line);
    printf("%i\n", ret);
    free(line);
    return(0);

}

有谁知道我的程序有什么问题?在我看来,s总是在我释放它之前分配。

标签: cfree

解决方案


推荐阅读