【fstat/stat/lstat系統調用】
功能描述:
擷取一些檔案相關的資訊。
用法:
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int stat(const char *path, struct stat *buf);
int fstat(int filedes, struct stat *buf);
int lstat(const char *path, struct stat *buf);
參數:
path:檔案路徑名。
filedes:檔案描述詞。
buf:是以下結構體的指標
struct stat {
dev_t st_dev; /* 檔案所在裝置的標識 */
ino_t st_ino; /* 檔案結點號 */
mode_t st_mode; /* 檔案保護模式 */
nlink_t st_nlink; /* 硬串連數 */
uid_t st_uid; /* 檔案使用者標識 */
gid_t st_gid; /* 檔案使用者組標識 */
dev_t st_rdev; /* 檔案所表示的特殊裝置檔案的裝置標識 */
off_t st_size; /* 總大小,位元組為單位 */
blksize_t st_blksize; /* 檔案系統的塊大小 */
blkcnt_t st_blocks; /* 分配給檔案的塊的數量,512位元組為單元 */
time_t st_atime; /* 最後訪問時間 */
time_t st_mtime; /* 最後修改時間 */
time_t st_ctime; /* 最後狀態改變時間 */
};
返回說明:
成功執行時,返回0。失敗返回-1,errno被設為以下的某個值
EBADF: 檔案描述詞無效
EFAULT: 地址空間不可訪問
ELOOP: 遍曆路徑時遇到太多的符號串連
ENAMETOOLONG:檔案路徑名太長
ENOENT:路徑名的部分組件不存在,或路徑名是空字串
ENOMEM:記憶體不足
ENOTDIR:路徑名的部分組件不是目錄
檔案和目錄
stat,fstat和lstat函數
#i nclude<sys/stat.h>
int stat(const char *restrict pathname,struct stat *restrict buf);
int fstat(int fields,struct stat *buf);
int lstat(const char *restrict pathname,struct stat *restrict buf);
傳回值:若成功則返回0,失敗則返回-1
一旦給出pathname,stat函數就返回與此命名檔案有關的資訊結構,fstat函數擷取已在描述符fields上開啟檔案的有關資訊。
lstat函數類似於stat.但是當命名的檔案是一個符號連結時,lstat返回該符號連結的有關資訊,而不是由該符號連結引用檔案
的資訊。第二個參數buf是指標,它指向一個我們必須提供的結構,這些函數填寫由buf指向的結構。該結構的實際定義可能隨實現
有所不同.
struct stat{
mode_t st_mode; //檔案類型和許可權資訊
ino_t st_ino; //i結點標識
dev_t st_dev; //device number (file system)
dev_t st_rdev; //device number for special files
nlink_t st_nlink; //符號連結數
uid_t st_uid; //使用者ID
gid_t st_gid; //組ID
off_t st_size; //size in bytes,for regular files
time_t st_st_atime; //最後一次訪問的時間
time_t st_mtime; //檔案內容最後一次被更改的時間
time_t st_ctime; //檔案結構最後一次被更改的時間
blksize_t st_blksize; //best I/O block size
blkcnt_t st_blocks; //number of disk blocks allocated
};
檔案類型:
普通檔案,目錄檔案,塊特殊檔案,字元特殊檔案,通訊端,FIFO,符號連結.
檔案類型資訊包含在stat結構的st_mode成員中,可以用如下的宏確定檔案類型,這些宏是stat結構中的st_mode成員.
S_ISREG();S_ISDIR();S_ISCHR();S_ISBLK();S_ISFIFO();S_ISLNK();S_ISSOCK()
樣本:
#i nclude<iostream>
int main(int argc,char* argv[])
{
int i;
struct stat buf;
char * ptr;
for(i=1;i<argc;i++)
{
if(lstat(argv[i],&buf)<0)
{
perror("錯誤原因是:");
continue;
}
if (S_ISREG(buf.st_mode))
ptr="普通檔案";
if (S_ISDIR(buf.st_mode))
ptr="目錄";
//......and so on...
cout<<"參數為:"<<argv[i]<<"的標識是一個"<<ptr<<endl;
}
exit(0);
}