c - 如何创建一个 (C) 函数来使用 'read' 将文件中的数据读取到链接列表中?

标签 c io linked-list

我正在尝试创建一个函数,将给定文件中的所有字符读取到链接列表中,并返回指向该列表的指针。我无法使用 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 。这里您使用的是原始系统调用,例如 openread完成您的任务,并且 EOF与这些无关。

您可以查看manual page for read 看看到达文件末尾时会发生什么:

ssize_t read(int fd, void *buf, size_t count);

read() attempts to read up to count bytes from file descriptor fd into the buffer starting at buf.

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/

相关文章:

c - “scanf_s”函数在我的 C 项目中运行不佳

java - FileWriter 未正确写入目录

c - 尝试写入文件时 fprintf 不起作用

java - 你如何从 txt 文件中读取所有 double ?

C - 链表打印顺序错误

c - 编写 Vending 程序,while 语句不会中断?

c - C 中的递归合并排序和内存分配

c - 如何在c中检查服务器是否启动?

python - 如何在列表 C++ 中存储套接字

C++:从链表中提取值