我正在尝试创建一个函数,将给定文件中的所有字符读取到链接列表中,并返回指向该列表的指针。我无法使用 fopen、fread 或 fclose。我已经确认,如果对字符串进行操作,这是有效的代码:
请注意,ft_lstnew 创建一个链接,其内容作为第一个权限,返回指向该链接的指针。
head = ft_lstnew(&str[i++], 1);
curr = head;
while(str[i])
{
curr->next = ft_lstnew(&str[i++], 1);
curr = curr->next;
}
curr->next = ft_lstnew(&str[i], 1);
如何更改此代码以使用读取函数对文件中的字符而不是字符串进行操作?
我的尝试
t_list *ft_lstnew(void const *content, size_t content_size);
t_list *read_tetriminos(char *file)
{
int fd;
char c;
t_list *curr;
t_list *head;
fd = open(file, O_RDONLY, 0);
read(fd, &c, 1);
head = ft_lstnew(&c, 1);
curr = head;
while(curr->content != EOF)
{
read(fd, &c, 1);
curr->next = ft_lstnew(&c, 1);
curr = curr->next;
}
close(fd);
return(head);
}
最佳答案
你就快到了。你做错的唯一一件事是假设 read
会写EOF
当到达文件末尾时在提供的缓冲区内。 EOF
只是 stdio.h
提供的更高级别函数使用的特殊值表示 FILE
的结束目的已经达到。此外,EOF
不是char
,但是 int
。这里您使用的是原始系统调用,例如 open
和read
完成您的任务,并且 EOF
与这些无关。
您可以查看manual page for read
看看到达文件末尾时会发生什么:
ssize_t read(int fd, void *buf, size_t count);
read()
attempts to read up tocount
bytes from file descriptorfd
into the buffer starting atbuf
.On files that support seeking, the read operation commences at the file offset, and the file offset is incremented by the number of bytes read. If the file offset is at or past the end of file, no bytes are read, and
read()
returns zero.
因此,你的程序可以像这样重写(我还添加了一些错误检查):
t_list *read_tetriminos(char *file)
{
int fd;
ssize_t nread;
char c;
t_list *curr;
t_list *head;
fd = open(file, O_RDONLY);
if (fd == -1) {
// Open failed.
return NULL;
}
nread = read(fd, &c, 1);
if (nread == -1) {
// Read error.
return NULL;
} else if (nread == 0) {
// File is empty.
return NULL;
}
head = ft_lstnew(&c, 1);
curr = head;
while (read(fd, &c, 1) == 1) // You can check for errors here too, this is just simplified.
{
curr->next = ft_lstnew(&c, 1);
curr = curr->next;
}
close(fd);
return head;
}
关于c - 如何创建一个 (C) 函数来使用 'read' 将文件中的数据读取到链接列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59051711/