【发布时间】:2016-11-15 01:40:02
【问题描述】:
我正在尝试一次读取一行文件,具有不同的缓冲区长度。我将文件 desc 传递给 get_next_line 函数并将该行分配给指针。问题是当缓冲区长度很长时,有时它会打印文件的其余部分,当我传递 2 个不同的文件描述符时,我得到一个段错误。我认为这与将字符串保存在节点中并在 fd 相同时找到相同的节点有关。 我没有看到我在这里做错了什么。
get_next_line.c
#include "get_next_line.h"
#include <fcntl.h>
#include <stdio.h>
/*
** CREATE THE NEXT NODE TO ADD TO THE LINKEDLIST.
**
*/
t_node *create_node(char *buffer, int fd)
{
int i;
t_node *new;
i = 0;
while (*buffer != '\n')
buffer++;
if (*buffer == EOF)
return 0;
++buffer;
new = malloc(sizeof(t_node));
new->fd = fd;
new->next = NULL;
new->str = malloc(sizeof(char *));
while (buffer[i] != '\n')
{
new->str[i] = (char)malloc(sizeof(char));
new->str[i] = buffer[i];
i++;
}
return (new);
}
/*
** SEARCH THE LIST FOR FD AND GET THE OVERFLAP STRING FROM
** LAST READ.
*/
char *get_overlap(t_node **root, int fd)
{
t_node *conductor;
if (*root == NULL)
return (NULL);
conductor = *root;
while (conductor->fd != fd && conductor != 0)
conductor = conductor->next;
if (conductor == NULL)
return (NULL);
return (conductor->str);
}
/*
** CALL THE CREATE NODE FUNCTION AND ADD IT TO THE LINKEDLIST.
**
*/
void save_overlap(char buffer[], t_node **root, int fd)
{
t_node **conductor;
t_node *new;
new = create_node(buffer, fd);
if (*root == NULL)
*root = new;
else
{
conductor = root;
while (*conductor != NULL)
{
if ((*conductor)->fd == fd)
{
(*conductor)->str = new->str;
break;
}
if ((*conductor)->next == NULL)
{
(*conductor)->next = new;
break;
}
*conductor = (*conductor)->next;
}
}
}
/*
** PREPEND THE PREVIOUS OVERLAP IN BUFFER TO LINE STRING.
**
*/
void prepend_overlap(char *str, char ***line, int *i)
{
int b = *i;
while (str[b])
{
(**line)[b] = (char)malloc(sizeof(char));
(**line)[b] = str[b];
b++;
}
*i = b;
}
/*
** GET A SINGLE LINE AT A TIME FROM A FILE
** WHILE ALSO KEEPING TRACK OF THE FD.
*/
int get_next_line(const int fd, char **line)
{
char buffer[BUFF_SIZE + 1];
int i;
int j;
char *overlap_str;
static t_node *root;
i = 0;
j = 0;
overlap_str = get_overlap(&root, fd);
if(overlap_str != NULL)
prepend_overlap(overlap_str, &line, &i);
read(fd, buffer, BUFF_SIZE);
while (buffer[j] != '\n')
{
if (j == BUFF_SIZE)
{
(*line)[i] = (char)malloc(sizeof(char));
(*line)[i] = buffer[j];
j = 0;
read(fd, buffer, BUFF_SIZE);
continue;
}
(*line)[i] = (char)malloc(sizeof(char));
(*line)[i] = buffer[j];
i++;
j++;
}
(*line)[i] = '\0';
printf("%s\n", *line);
save_overlap(buffer, &root, fd);
return (0);
}
int main()
{
int fd = open("test", O_RDONLY);
//int fdt = open("test2", O_RDONLY);
char *line;
get_next_line(fd, &line);
get_next_line(fd, &line);
}
get_next_line.h
#ifndef GET_NEXT_LINE_H
# define GET_NEXT_LINE_H
# define BUFF_SIZE 32
#include <fcntl.h>
int get_next_line(const int fd, char **line);
typedef struct s_node
{
int fd;
char *str;
struct s_node *next;
}t_node;
#endif
它适用于单个文件描述符,例如,我可以只传递 fd 而不是 fdt,它会起作用,除非我将缓冲区大小设置为 120 或更大,例如,它会打印出我想要的更多。我只想要'\n'之前的那一行。
【问题讨论】:
标签: c pointers linked-list file-descriptor