檔案管理(四)
阿新 • • 發佈:2018-12-03
編寫程式實現以下功能:
1.新建檔案,設定檔案許可權遮蔽字為0;
2.建立該檔案的硬連結檔案,列印硬連結檔案的inode節點號和檔案大小;
3.建立該檔案的軟連結檔案,列印軟連結檔案的inode節點號和檔案大小;列印軟連結檔案中的內容;
4.列印原始檔的inode節點號,檔案大小和連結數目;
5.呼叫unLink對原始檔進行操作,列印原始檔連結數目;
在進行程式編寫之前,我們應當瞭解檔案的軟連結和硬連結的含義及兩者的區別。
1.軟連結,以路徑的形式存在。類似於Windows作業系統中的快捷方式
2.軟連結可以 跨檔案系統 ,硬連結不可以
3.軟連結可以對一個不存在的檔名進行連結
4.軟連結可以對目錄進行連結
軟連結檔案存放的內容是原檔案的路徑名。
硬連結:硬連結檔案是對原檔案的檔名
Linux下的每個檔案都具有各自的許可權位,使用者要想對檔案進行某種操作,就必須具有相應許可權。Linux下的檔案許可權位如下表所示:
st_mode | 含義 |
---|---|
S_IRUSR | 當前使用者讀(0400) |
S_IWUSR | 當前使用者寫(0200) |
S_IXUSR | 當前使用者執行(0100) |
S_IRWXU | 當前使用者讀、寫、執行(0700) |
S_IRGRP | 組內使用者讀(0040) |
S_IWGRP | 組內使用者寫(0020) |
S_IXGRP | 組內使用者執行(0010) |
S_IRWXG | 組內使用者讀、寫、執行(0070) |
S_IROTH | 組外使用者讀(0004) |
S_IWOTH | 組外使用者寫(0002) |
S_IXOTH | 組外使用者執行(0001) |
S_IRWXO | 組外使用者讀、寫、執行(0007) |
當用戶建立一個檔案時,需要為新的檔案指定一個許可權字,在實際應用中,系統有時不希望使用者設定所有的許可權。因此可以通過umask函式設定許可權遮蔽字,直接將不需要使用者干預的檔案許可權進行遮蔽,這樣即使使用者設定了相關檔案許可權位,系統也會將其忽略,仍然將其設為0;
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
int main()
{
umask(0);
struct stat statbuf;
int fd = open("file",O_CREAT|O_RDWR);
if(fd < 0)
perror("open");
char *str = "hello world";
if(write(fd,str,strlen(str)) < 0)
perror("write");
link("./file","./hard_link");
if(lstat("hard_link",&statbuf) < 0)
perror("lstat");
printf("The hard_link's inode is: %d\n",statbuf.st_ino);
printf("The hard_link's size is: %d\n",statbuf.st_size);
symlink("file","sort_link");
if(lstat("sort_link",&statbuf) < 0)
perror("lstat");
printf("The sort_link's inode is: %d\n",statbuf.st_ino);
printf("The sort_link's size is: %d\n",statbuf.st_size);
char buf[4];
readlink("sort_link",buf,4);
printf("The sort_link is: %s\n",buf);
if(lstat("file",&statbuf) < 0)
perror("lstat");
printf("The file's inode is: %d\n",statbuf.st_ino);
printf("The file's size is: %d\n",statbuf.st_size);
printf("The frist linknum is: %d\n",statbuf.st_nlink);
unlink("file");
if(lstat("file",&statbuf) < 0)
perror("lstat");
printf("The second linknum is: %d\n",statbuf.st_nlink);
close(fd);
return 0;
}
程式執行結果:
我們可以看到,在第二次利用lstat獲取file的資訊時,提示沒有file,這正是進行ulink的結果。
ulink函式的作用:刪除目錄相併減少一個連線數,如果連結數為0並且沒有任何程序開啟該檔案,該檔案內容才能被真正刪除,但是若又程序打開了該檔案,則檔案暫時不刪除直到所有開啟該檔案的程序都結束時檔案才能被刪除。
因此,執行結果中顯示的第二個linknum仍然是第一個的值。
實驗成功。