【问题标题】:Why are directory files not read using fread?为什么不使用 fread 读取目录文件?
【发布时间】:2014-09-18 19:59:54
【问题描述】:

我正在阅读 Maurice Bach 的 Unix Book 中的一个示例。他编写了一个简单的复制程序,如下所述。但是,当输入文件是目录文件时,它会失败。我确实偶然发现了opendir 和其他一些这样的 API——我应该使用它吗?

如果二进制文件可以使用它,为什么目录文件被认为是不同的?在 Unix 中,不是所有的东西都抽象为一个文件,不管它是如何被程序解释的。

另外,我怎样才能扩展这个程序来支持目录文件,然后创建一个 mknod 呢?我想对此进行测试,假设我在/home/user1 并执行$./copy /home/user user-home-clonemknod 以查看该目录与主目录有何不同。我猜user-home-clone 可能没有对自身的引用,但是/home/user 中的所有其他文件[即使它会在 /home/user 中有一个名为 user-home-clone 的文件],因为它不是当我们执行复制命令时在那里?

#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>

char buffer[2048];

int copy(FILE *source, FILE *destination)
{
    int count;
    while ((count = fread(buffer, 1, sizeof buffer , source)) > 0)
    {
        fwrite(buffer, 1, count, destination);
    }
    return 0;
}

int main(int argc, char* argv[])
{
    int status;
    FILE *source;
    FILE *destination;

    if (argc != 3)
    {
        printf("%s takes exactly 3 arguments\n", argv[0]);
        exit(1);
    }
    source = fopen(argv[1], "r");
    if (source == NULL)
    {
        printf("%s can't  be opened for reading\n", argv[1]);
        exit(1);
    }
    destination = fopen(argv[2], "wb");
    if (destination == NULL)
    {
        printf("%s can't  be opened for writing\n", argv[2]);
        exit(1);
    }
    if (copy(source, destination) == 0)
    {
        status = 0;
    }
    else
    {
        status = 1;
    }

    fclose(source);
    fclose(destination);
    exit(status);
}

我使用 Centos 6.5 Linux Ext4 文件系统

【问题讨论】:

  • 错误信息属于stderr,应该提供更多信息:if (source == NULL) { perror(argv[1]); exit(1);}
  • 感谢您的澄清。会看看 perror 。

标签: c file directory mknod


【解决方案1】:

在早期版本的 Unix 中,目录文件可以作为二进制文件读取。但是,当添加网络和其他类型的虚拟文件系统时,此功能被删除,因为不同的文件系统以不同的方式实现目录。虽然驱动程序在技术上可以模拟这些目录的字节流结构,但它并不被视为有用的功能。目录应被视为不透明的抽象集合,并使用特定于目录的函数进行访问。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-06
    • 1970-01-01
    • 1970-01-01
    • 2019-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-18
    相关资源
    最近更新 更多