一、頭文件
#include<unistd.h>
二、函數原型
int unlink(const char *pathname);
三、函數介紹
unlink()函數功能即為刪除文件。執行unlink()函數會刪除所給參數指定的文件。
注意:
執行unlink()函數並不一定會真正的刪除文件,它先會檢查文件系統中此文件的連接數是否為1,如果不是1說明此文件還有其他鏈接對象,因此只對此文件的連接數進行減1操作。若連接數為1,並且在此時沒有任何進程打開該文件,此內容才會真正地被刪除掉。在有進程打開此文件的情況下,則暫時不會刪除,直到所有打開該文件的進程都結束時文件就會被刪除。
返回值:成功返回0,失敗返回 -1
四、代碼示例
#include<unistd.h> #include<stdio.h> #include<fcntl.h> #include<assert.h> int main() { int fd = open("test.txt", O_RDWR | O_TRUNC | O_CREAT, 0664); assert(fd != -1); if(unlink("test.txt") < 0) { printf("unlink errpr!\n"); } char buff[128] = {0}; write(fd, "hello world!", 12); if(lseek(fd,0,SEEK_SET) == -1) { printf("lseek error!\n"); } read(fd, buff, 12); printf("%s\n",buff); return 0; }