#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此文件。即unlink后,所有使用該文件的進程結束以后,文件才會被刪除,這些進程在未結束時,unlink刪除的只是文件的目錄項(此時文件已經具有了被刪除的條件,硬鏈接數為0),文件本身的內容即inode未被刪除。以如下代碼為例。
返回值: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