標籤:
_stat函數的功能
_stat函數用來擷取指定路徑的檔案或者檔案夾的資訊。
函式宣告
int _stat( const char *path, struct _stat *buffer );
參數:
path——檔案或者檔案夾的路徑
buffer——擷取的資訊儲存在記憶體中
傳回值:
正確——返回0
錯誤——返回-1,具體錯誤碼儲存在errno中
struct _stat結構體
_stat結構體是檔案(夾)資訊的結構體,定義如下:
struct stat { _dev_t st_dev; //檔案所在磁碟機號 _ino_t st_ino; //inode,FAT、NTFS檔案系統無意義 unsigned short st_mode; //檔案、檔案夾的標誌 short st_nlink; //非NTFS系統上通常為1 short st_uid; //UNIX系統上為userid,windows上為0 short st_gid; //UNIX系統上為groupid,windows上為0 _dev_t st_rdev; //磁碟機代號,與st_dev相同 _off_t st_size; //檔案位元組數 time_t st_atime; //上次訪問時間 time_t st_mtime; //上次修改時間 time_t st_ctime; //建立時間 };
以上資訊就是可以通過_stat函數擷取的所有相關資訊,一般情況下,我們關心檔案大小和建立時間、訪問時間、修改時間。
例子
註:該例子來自MSDN,http://msdn.microsoft.com/en-us/library/14h5k7ff.aspx
// crt_stat.c// This program uses the _stat function to// report information about the file named crt_stat.c. #include <time.h>#include <sys/types.h>#include <sys/stat.h>#include <stdio.h>#include <errno.h>int main( void ){ struct _stat buf; int result; char timebuf[26]; char* filename = "crt_stat.c"; errno_t err; // Get data associated with "crt_stat.c": result = _stat( filename, &buf ); // Check if statistics are valid: if( result != 0 ) { perror( "Problem getting information" ); switch (errno) { case ENOENT: printf("File %s not found.\n", filename); break; case EINVAL: printf("Invalid parameter to _stat.\n"); break; default: /* Should never be reached. */ printf("Unexpected error in _stat.\n"); } } else { // Output some of the statistics: printf( "File size : %ld\n", buf.st_size ); printf( "Drive : %c:\n", buf.st_dev + ‘A‘ ); err = ctime_s(timebuf, 26, &buf.st_mtime); if (err) { printf("Invalid arguments to ctime_s."); exit(1); } printf( "Time modified : %s", timebuf ); }}
輸出大致如下:
File size :732
Drive :C:
Time modified :Thu Feb 07 14:39:36 2002
支援不同時間長度和檔案長度
_stat函數中時間定義為64位,檔案長度也定義為32位,同時使用char*表示檔案名稱。我們知道可以時間可以定義為64位和32位:__time64和__time32,檔案名稱也可以用寬字元來表示,檔案長度也可以定義為64位。因此該函數有很多變體,這些函數用法都是一樣的,我們根據具體情況選擇使用哪個函數。
int _stat( const char *path, struct _stat *buffer );int _stat32( const char *path, struct __stat32 *buffer );int _stat64( const char *path, struct __stat64 *buffer );int _stati64( const char *path, struct _stati64 *buffer );int _stat32i64(str const char *path, struct _stat32i64 *buffer );int _stat64i32(str const char *path, struct _stat64i32 *buffer );int _wstat( const wchar_t *path, struct _stat *buffer );int _wstat32( const wchar_t *path, struct __stat32 *buffer );int _wstat64( const wchar_t *path, struct __stat64 *buffer );int _wstati64( const wchar_t *path, struct _stati64 *buffer );int _wstat32i64( const wchar_t *path, struct _stat32i64 *buffer );int _wstat64i32( const wchar_t *path, struct _stat64i32 *buffer );
【轉】windows c++擷取檔案資訊——_stat函數的使用