#include <sys/stat.h>int stat( const char *restrict pathname, struct stat *restrict buf );int fstat( int filedes, struct stat *buf );int lstat( const char *restrict pathname, struct stat *restrict buf );三個函數的返回值:若成功則返回0,若出錯則返回-1
關于上面函數聲明中的restrict關鍵字的解釋,可參考:http://blog.csdn.net/lovekatherine/article/details/1891806(具體如下)
今天讀APUE,看到某個函數原型的聲明:
int stat ( const char * restrict pathname,struct stat * restrict buf);
這里的restrict讓我覺得有些疑惑,一查原來是C99中增加的關鍵字那么restrict的意義是什么呢?
One of the new features in the recently apPRoved C standard C99, is the restrict pointer qualifier. This qualifier can be applied to a data pointer to indicate that, during the scope of that pointer declaration, all data accessed through it will be accessed only through that pointer but not through any other pointer. The 'restrict' keyWord thus enables the compiler to perform certain optimizations based on the premise that a given object cannot be changed through another pointer. Now you're probably asking yourself, "doesn't const already guarantee that?" No, it doesn't. The qualifier const ensures that a variable cannot be changed through a particular pointer. However, it's still possible to change the variable through a different pointer.
概括的說,關鍵字restrict只用于限定指針;該關鍵字用于告知編譯器,所有修改該指針所指向內容的操作全部都是基于(base on)該指針的,即不存在其它進行修改操作的途徑;這樣的后果是幫助編譯器進行更好的代碼優化,生成更有效率的匯編代碼。
舉個簡單的例子
int foo (int* x, int* y){*x = 0;*y = 1;return *x;}
很顯然函數foo()的返回值是0,除非參數x和y的值相同??梢韵胂?,99%的情況下該函數都會返回0而不是1。然而編譯起必須保證生成100%正確的代碼,因此,編譯器不能將原有代碼替換成下面的更優版本
int f (int* x, int* y){*x = 0;*y = 1;return 0;}
啊哈,現在我們有了restrict這個關鍵字,就可以利用它來幫助編譯器安全的進行代碼優化了
int f (int *restrict x, int *restrict y){*x = 0;*y = 1;return *x;}
此時,由于指針 x 是修改 *x的唯一途徑,編譯起可以確認 “*y=1; ”這行代碼不會修改 *x的內容,因此可以安全的優化為 int f (int *restrict x, int *restrict y){*x = 0;*y = 1;return 0;}
最后注意一點,restrict是C99中定義的關鍵字,C++目前并未引入;在GCC可通過使用參數" -std=c99"來開啟對C99的支持。
一旦給出pathname,stat函數就返回與此命名文件有關的信息結構。fstat函數獲取已在描述符filedes上打開的有關信息。lstat函數類似于stat,但是當命名的文件是一個符號鏈接時,lstat返回該符號鏈接的有關信息,而不是由該符號鏈接引用文件的信息。
第二個參數buf是指針,它指向一個我們必須提供的結構。這些函數填寫由buf指向的結構。該結構的實際定義可能隨實現有所不同,但其基本形式是:
struct stat{ mode_t st_mode; /* file type & mode (permissions) */ ino_t st_ino; /* i-node number (serial number) */ dev_t st_dev; /* device number (file system) */ dev_t st_rdev; /* device number for special files */ nlink_t st_nlink; /* number of links */ uid_t st_uid; /* user ID of owner */ gid_t st_gid; /* group ID of owner */ off_t st_size; /* size in bytes, for regular files */ time_t st_atime; /* time of last access */ time_t st_mtime; /* time of last modification */ time_t st_ctime; /* time of last file status change */ blksize_t st_blksize; /* best I/O block size */ blkcnt_t st_blocks; /* number of disk blocks allocated */};
POSIX.1未要求st_rdev、st_blksize和st_blocks字段,Single UNIX Specification XSI擴展則定義了這些字段。
注意,該結構中的每一個成員都是基本系統數據類型。
使用stat函數最多的可能是ls -l命令,用其可以獲得有關一個文件的所有信息。
新聞熱點
疑難解答