1、程序示例
// lstat 或者 stat 需要包含的头文件
#include <sys/types.h>
#include <sys/stat.h>
// perror() 需要包含的头文件
#include<stdio.h>
// struct dirent 和 DIR 需要包含的头文件
#include <dirent.h>
//其它cout和ctime需要包含头文件
#include <iostream>
#include <time.h>
string path_Name = "/home/temp";
DIR *dirptr = NULL; //定义一个指向所打开的目录中文件的指针
char cFilePathName[128];
if ( ( dirptr= opendir( path_Name.c_str() )) == NULL )
{
perror("打开目录出错! "); // 这里的perror打印出对应的内容到标准输入终端,并紧接着打印出errno的宏定义的值(全局变量,表示上一次函数执行所返回的错误编号)所对应的错误信息提示字符串内容。
}
else
{
struct dirent * dircontent; //定义一个承接获取的目录中的文件信息的指针
while ( ( dircontent = readdir( dirptr) ) != NULL ) //会自动将dirptr加1指向下一个文件
{
if ( (0 == strcasecmp(dircontent ->d_name, ".")) || (0 == strcasecmp(dircontent ->d_name, "..")) )
{ continue; } //不对目录下的 . 和 .. 做处理。
sprintf( cFilePathName, "%s/%s", path_Name.c_str() , dircontent->d_name);
struct stat file_info_stru;
if ( lstat( cFilePathName , &file_info_stru ) < 0 ) // 通过 lstat 或者 stat 获取文件状态,返回0表示正常,返回值 -1表示异常。
{
perror( "获取文件信息异常!" );
}
else
{
//获取文件信息正常
// 文件的大小,字节
cout << "*******文件名: " << cFilePathName << endl;
cout << "size of the file in bytes: " << file_info_stru.st_size << endl;
// 文件创建的时间
cout << "time of creation of the file: " << ctime (file_info_stru.st_ctime) << endl;
// 最近一次修改的时间
cout << "time of last modification of the file: " << ctime (file_info_stru.st_mtime) << endl;
// 最近一次访问的时间
cout << "time of last access of the file: " << ctime (file_info_stru.st_atime)<< endl;
}
}
closedir(dirptr); //关闭目录
}
2、struct dirent 结构体
主要是通过readdir 获取到的目录下一个文件的简单信息,包括文件名、文件名长度、文件类型、在目录文件中的偏移量。
struct dirent
{
long d_ino; /* inode number 索引节点号 */
off_t d_off; /* offset to this dirent 在目录文件中的偏移 */
unsigned short d_reclen; /* length of this d_name 文件名长 */
unsigned char d_type; /* the type of d_name 文件类型 */
char d_name [NAME_MAX+1]; /* file name (null-terminated) 文件名,最长255字符 */
}
3、stat 结构体
stat结构体是文件(夹)信息的结构体,通常用的比较多的是文件大小(st_size)、访问时间(st_atime)、创建时间(st_ctime)、修改时间(st_mtime)。
struct stat
{
dev_t st_dev; /* ID of device containing file -文件所在设备的ID*/
ino_t st_ino; /* inode number -inode节点号*/
mode_t st_mode; /* protection -保护模式?*/
nlink_t st_nlink; /* number of hard links -链向此文件的连接数(硬连接)*/
uid_t st_uid; /* user ID of owner -user id*/
gid_t st_gid; /* group ID of owner - group id*/
dev_t st_rdev; /* device ID (if special file) -设备号,针对设备文件*/
off_t st_size; /* total size, in bytes -文件大小,字节为单位*/
blksize_t st_blksize; /* blocksize for filesystem I/O -系统块的大小*/
blkcnt_t st_blocks; /* number of blocks allocated -文件所占块数*/
time_t st_atime; /* time of last access -最近存取时间*/
time_t st_mtime; /* time of last modification -最近修改时间*/
time_t st_ctime; /* time of last status change - */
};
4、errno.h说明
errno.h属于C标准函式库里的头文件,该头文件主要是将一些表示错误的码,定义为整数值的宏定义:
5、perror()打印错误日志的方法说明
perror(s) 用来将上一个函数发生错误的原因输出到标准设备(stderr)。参数 s 所指的字符串会先打印出,后面再加上错误原因字符串。此错误原因依照全局变量errno的值来决定要输出的字符串。
在库函数中有个errno变量,每个errno值对应着以字符串表示的错误类型。当你调用某些函数出错时,该函数已经重新设置了errno的值。perror函数只是将你输入的一些信息和errno所对应的错误一起输出。