獲取文件信息
C++標準庫提供了對文件內容處理的支持,但並不直接對文件基本信息的獲取和修改。所以,獲取文件的基本可以藉助於C庫中
定義的結構和函數。
在<sys/stat.h>頭文件中,定義了一個結構stat,它是用來描述文件元數據結構的。其定義如下:
struct stat { _dev_t st_dev; _ino_t st_ino; unsigned short st_mode; short st_nlink; short st_uid; short st_gid; _dev_t st_rdev; _off_t st_size; time_t st_atime; time_t st_mtime; time_t st_ctime; };
time_t數據類型表示的時間(日曆時間)是從一個時間點(例如:1970年1月1日0時0分0秒)到此時的秒數。在time.h中,可以看到time_t是一個長整型數:
#ifndef _TIME32_T_DEFINED typedef _W64 long __time32_t; /* 32-bit time value */ #define _TIME32_T_DEFINED #endif #ifndef _TIME64_T_DEFINED typedef __int64 __time64_t; /* 64-bit time value */ #define _TIME64_T_DEFINED #endif
微軟在visual C++中採用 __time64_t數據類型來保存日曆時間,並通過_time64()函數來獲得日曆時間 (而不是通過使用32位字的
time()函數)。
time_t類型的數據便於計算機的處理,但是不便於用戶閱讀,因此,可用函數 ctime_s()將time_t類型的數據轉換成字符串形式,然後再輸出給用戶。
一個獲取文件信息的例子:
#include <iostream> #include <ctime> #include <sys/stat.h> //定義了一個結構stat #include <sys/types.h> #include <cstring> using std::cout; using std::cin; using std::endl; int main() { struct stat fileInfo; //包含文件信息的一個結構體 char message[30]; //用於保存 ctime_s()函數返回的字符串 char path[50]; //文件夾或者的路徑 cin>>path; stat(path, &fileInfo); //獲得一個文件的信息 cout<<"Type: "; if((fileInfo.st_mode & S_IFMT) == S_IFDIR) //判斷是否是一個目錄 cout<<"Directory\n"; else cout<<"File\n"; cout<<"Size: "<<fileInfo.st_size<<endl; //文件大小 cout<<"Device: "<<(char)(fileInfo.st_dev + 'A')<<endl; //文件磁盤號 ctime_s(message, 29, &fileInfo.st_ctime); //獲得文件創建的時間 cout<<"Create: "<<message; ctime_s(message, 29, &fileInfo.st_mtime); //獲得文件最後修改的時間 cout<<"Modified: "<<message<<endl; time_t y; return 0; }
關於文件結構的信息還有很多,也不知結構stat這一個,想了解更多,看下面的這個鏈接:
http://www.blue1000.com/bkhtml/2010-04/67485.htm