获取文件信息

获取文件信息

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

 


 

发布了37 篇原创文章 · 获赞 16 · 访问量 7万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章