天天看點

stat檢視檔案屬性

頭檔案:

#include <sys/types.h >
#include <sys/stat.h>
#include <unistd.h>      

檢視檔案屬性函數有:

int stat(const char *path,struct stat *buf);
int fstat(int fd,struct stat *buf);
int lstat(const char *path,struct stat *buf);      

stat函數:

函數原型: ​​

​int stat (const chat *path,struct stat *buf);​

​​ 參數一:需要檢視的檔案路徑

參數二:檢視後的檔案屬性儲存位址

傳回值:成功傳回0,失敗傳回-1

stat結構體如下:

struct stat { 包含主次裝置号 /dev/sda

dev_t st_dev; //dev_t —》裝置号類型,容納該檔案的那個裝置的裝置号。 普通檔案所在的儲存器裝置号 major()主裝置号

ino_t st_ino; //inode number —》minor()次裝置号

mode_t st_mode; //—》檔案權限(包含類型)

nlink_t st_nlink; //—》Inode硬連結數●講清硬連結與軟連接配接的差別,即指令:ln -s為軟連接配接,沒有-s為硬連結

uid_t st_uid; //—》檔案屬主(owner, 擁有者)的使用者id

gid_t st_gid; //—》檔案屬主(owner)的組id

dev_t st_rdev; //—》檔案的裝置号(假如該檔案是裝置) 特殊檔案裝置号(驅動檔案)

off_t st_size; //檔案内容的長度//st_size對普通檔案(文本檔案,二進制檔案),檔案内容的長度

//st_size對目錄而言,檔案長度通常是一個數的倍數。●目錄的内容是檔案項數組

//st_size對符号連結檔案,符号連結檔案的内容是它指向的檔案的檔案名●大小為指向檔案名的位元組

blksize_t st_blksize; //block size—》塊大小(與具體的硬體相關)

blkcnt_t st_blocks; //—》檔案占多少塊(block,在linux下面每個block占512bytes)

time_t st_atime; //access time —》最後通路"檔案内容"的時間, read/write

time_t st_mtime; //modify time —》最後修改"檔案内容"的時間,

time_t st_ctime; //change time —》最後改變"檔案屬性"的時間,●即改變i-node資訊

};

詳細解釋:

st_dev —》普通檔案所在的儲存器裝置号,即硬碟裝置

st_redv—》驅動裝置号

st_mode—》檔案權限與檔案類型擷取

使用例子:

判斷檔案類型:if(S_ISREG(filemsg.st_mode));

擷取檔案權限:if(S_IFREG&filemsg.st_mode);

使用stat函數擷取檔案權限與檔案大小

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int main(int argv,char **argc)
{
    if(argv<2)
    {
        perror("stat fail no file:");
    }
    struct stat filemsg;
    stat(argc[1],&filemsg);
    if( S_IRUSR&filemsg.st_mode|| S_IWUSR && filemsg.st_mode)
    {  
        printf("USR have read or write\n");//判斷使用者是否有讀寫程式
    }
    if(S_IRGRP&filemsg.st_mode|| S_IWGRP && filemsg.st_mode )
    {  
        printf("group have read or write\n");//判斷使用者組是否有讀寫程式
    }
    printf("the file size=%d\n",(int)filemsg.st_size);//列印檔案大小
    
}      

測試檔案權限函數access();

頭檔案:

#include <unistd.h>

函數原型:

int access(const char *pathname ,int mode);

參數一:要測試的檔案路徑

參數二:要測試的權限

R_OK—>可讀

W_OK—》可寫

X_OK—》可執行

F_OK—》檔案是否存在

傳回值:成功傳回0,失敗傳回-1

擷取檔案路徑函數

函數原型:

char *getwd(char *buf);      

功能:擷取檔案路徑并存放到buf中

注意:該函數存在溢出的危險,是以應謹慎使用

擷取環境變量的值:

頭檔案:

#include <stdlib.h>      

函數原型:

char *getenv(const char *name);      

删除檔案函數

頭檔案:

#include <stdio.h>      
int remove(const char *pathname);      

繼續閱讀