最近看Linux的文件,发现Unix的文件系统跟Win的相差甚远。有一个比较大的区别就是连接。
Unix可以通过link函数来为一个文件命名多个名字:
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
int main(void) {
int fd;
fd = open("tmp", O_RDWR | O_CREAT | O_APPEND, O_SYNC);
if (fd < 0) {
fprintf(stderr, "Can not create <tmp>/n");
exit(1);
}
write(fd, "Hello World", 11);
close(fd);
if (link("tmp", "newtmp") != 0) {
fprintf(stderr, "Can not link to <tmp>/n");
exit(1);
}
return 0;
}
我们创建了一个文件tmp,然后写入字符串Hello World,然后通过link函数创建一个连接到tmp的新文件名,现在tmp和newtmp都是指向同一个文件。所以我们查看这两个文件的时候可以发现他们的信息是一模一样的。
然后我们修改其中的一个连接:
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
int main() {
int fd;
fd = open("tmp", O_WRONLY | O_TRUNC);
if (fd < 0) {
fprintf(stderr, "Can not open <tmp>/n");
exit(1);
}
write(fd, "This is changed content", sizeof("This is changed content"));
close(fd);
return 0;
}
通过cat ./tmp和cat ./newtmp发现,他们的内容是完全一样的。