【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;
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);
}