#include <unistd.h>
int link(const char *oldpath, const char *newpath);
作用:创建一个硬链接 0成功 -1 失败
//代码
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char* argv[])
{
if(argc < 3)
{
printf("a.out oldpath newpath\n");
exit(0);
}
int ret = link(argv[1], argv[2]);
if(ret == -1)
{
perror("link");
exit(1);
}
return 0;
}
#include <unistd.h>
int symlink(const char *oldpath, const char *newpath);
作用:创建一个软链接 0成功 -1失败
#include <unistd.h>
ssize_t readlink(const char *path, char *buf, size_t bufsiz);
作用:读一个软链接文件其本身的内容(即所链接的那个文件的文件路径或文件名),不是去读文件内容,将内容读到buff缓冲区(由用户维护)。 注意:该函数只能用于软链接文件。
返回值:成功则返回读取的字节数;失败则为-1。
//代码
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char* argv[])
{
if(argc < 2)
{
printf("a.out softlink\n");
exit(1);
}
char buf[512];
int ret = readlink(argv[1], buf, sizeof(buf));
if(ret == -1)
{
perror("readlink");
exit(1);
}
buf[ret] = 0; // 必须的,赋值为0或\0表示字符串结束符,该位及以后的字符不再输出,如果需要输出,可以采用循环一个一个的输出。
printf("buf = %s\n", buf);
return 0;
}
#include <unistd.h>
int unlink(const char *pathname);
作用:1. 如果是符号链接,删除符号链接(即直接删除该文件);2. 如果是硬链接,硬链接数减1(简化的FCB),当减为0时,释放数据块和inode;3. 如果文件硬链接数为1,但有进程已打开该文件,并持有文件描述符,则等该进程关闭该文件时,kernel才真正去删除该文件。第3个作用可以让临时文件关闭之后自己把自己删除掉,利用该特性创建临时文件,先open或creat创建一个文件,马上unlink此文件。以如下代码为例。
返回值:0成功 -1失败
//临时文件自己把自己干掉
[root@localhost work]# vim tmp.c
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
int main( )
{
int fd;
fd = open( "unlink",O_RDWR | O_CREAT,0664); //没有就创建该文件
if( fd == -1 )
{
perror("open file");
exit(1);
}
//打开后立即unlink文件(删除文件)
int fd1;
fd1==unlink("unlink");
if( fd1 == -1 )
{
perror("unlink file");
exit(1);
}
//为了证明该文件确实被存在过,则在关闭文件之间进行读、写和打印测试
int fd2;
fd2 = write(fd,"hello unlink!\n",14);
if( fd2 == -1 )
{
perror("write file");
exit(1);
}
int ret;
ret = lseek(fd,0,SEEK_SET); //将文件读写指针置于开头才能读
if( ret == -1 )
{
perror("lseek file");
exit(1);
}
int fd3;
char buff[15]={0};
fd3 = read(fd,buff,15);
if( fd3 == -1 )
{
perror("read file");
exit(1);
}
int fd4;
fd4 = write(1,buff,fd3);
if( fd4 == -1 )
{
perror("write file");
exit(1);
}
int ret1=close(fd);
if( ret1 == -1 )
{
perror("close file");
exit(1);
}
return 0;
}
[root@localhost work]# ./tmp
hello unlink!
[root@localhost work]# ls //可见,没有unlink文件,自己把自己删除了
english.txt ls-l.c stat.c statuse statuse.c tmp tmp.c