Nis*_*ant 2 c directory file mknod
我正在通过莫里斯巴赫的Unix书中的一个例子.他写了一个简单的复制程序,如下所述.但是,当inputfile是目录文件时,它会失败.我偶然发现了opendir其他一些这样的API - 我应该使用它吗?
如果二进制文件可以使用它,为什么目录文件被认为是不同的?在Unix中,并不是所有被抽象为文件的内容,无论程序如何解释它.
另外,我如何扩展此程序以支持目录文件,然后创建一个mknod?我想测试一下,假设我在/home/user1 并且做了一个$./copy /home/user user-home-clone,mknod看看该目录将如何与家庭不同.我想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);
}
Run Code Online (Sandbox Code Playgroud)
我使用Centos 6.5 Linux Ext4 Filesystem
在Unix的早期版本中,目录文件可以作为二进制文件读取.但是,当添加网络和其他类型的虚拟文件系统时,此功能被删除,因为不同的文件系统以不同方式实现目录.虽然在技术上驱动程序可以模拟这些目录的字节流结构,但它并不被视为有用的功能.应将目录视为不透明的抽象集合,并使用特定于目录的函数进行访问.