【发布时间】:2014-09-18 19:59:54
【问题描述】:
我正在阅读 Maurice Bach 的 Unix Book 中的一个示例。他编写了一个简单的复制程序,如下所述。但是,当输入文件是目录文件时,它会失败。我确实偶然发现了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);
}
我使用 Centos 6.5 Linux Ext4 文件系统
【问题讨论】:
-
错误信息属于stderr,应该提供更多信息:
if (source == NULL) { perror(argv[1]); exit(1);} -
感谢您的澄清。会看看 perror 。