c - 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
总是在我释放它之前分配。
解决方案
推荐阅读
- machine-learning - model.predict() 中的值是什么意思?
- nearest-neighbor - 贪心算法与最近邻算法
- python - 如何在 python 中使用 aws lambda 函数调用 bash 脚本?
- java - 我从 JavaFX 中的 XML 文件中获取的数据未显示在 TableView 中
- c++ - 无法获取 Internet 连接共享的 EveryConnectionCollection
- php - 在发送到数据库之前连接具有相同名称的文本字段值
- r - 对数据帧中的所有对运行方程,输出矩阵
- java - 按相似(不相同)的键对映射进行分组
- php - 使用 PHP 计算方阵
- javascript - 如果调用两次,递归如何工作?