在 Unix 系統中,當程式已經用 open() 開啟檔案並取得描述詞後,若需要取得該檔案的狀態,例如大小、權限、擁有者與時間戳記,可以呼叫 fstat()。它與 stat() 的主要差別是:stat() 接受路徑名稱,fstat() 則接受已開啟的檔案描述詞。
int fstat(int fildes, struct stat *buf);
fstat() 會把 fildes 所指向的檔案狀態複製到 buf 所指向的 struct stat 結構中。若程式只想對已開啟檔案做檢查,使用 fstat() 可避免再次傳入路徑,也能處理已刪除但仍被開啟的檔案。
成功時回傳 0;失敗時回傳 -1,並透過 errno 提供錯誤原因。
struct stat buf;
int fd = open("/etc/passwd", O_RDONLY);
fstat(fd, &buf);
printf("file size: %d\n", buf.st_size);此範例會取得 /etc/passwd 的大小。若系統輸出 705,表示該檔案當時的位元組數為 705。