C/C++打开目录、读取目录、获取目录下文件状态

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所对应的错误一起输出。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Linux环境下,也可以使用C++文件操作库和Linux系统调用来实现遍历路径下所有文件目录,并输出文件目录的名称。下面是一个示例代码: ```cpp #include <iostream> #include <fstream> #include <dirent.h> #include <sys/stat.h> void traverseDir(const std::string& path) { DIR* dir = opendir(path.c_str()); if (!dir) { std::perror("opendir"); return; } struct dirent* entry; while ((entry = readdir(dir)) != nullptr) { if (entry->d_name[0] == '.') { continue; // skip hidden files and directories } std::string fullPath = path + "/" + entry->d_name; struct stat fileStat; if (lstat(fullPath.c_str(), &fileStat) == -1) { std::perror("lstat"); continue; } if (S_ISDIR(fileStat.st_mode)) { std::cout << "Directory: " << fullPath << std::endl; traverseDir(fullPath); } else if (S_ISREG(fileStat.st_mode)) { std::cout << "File: " << fullPath << std::endl; } } closedir(dir); } int main(int argc, char* argv[]) { if (argc != 2) { std::cerr << "Usage: " << argv[0] << " <directory>" << std::endl; return 1; } traverseDir(argv[1]); return 0; } ``` 这个程序与前面的示例非常相似,唯一的区别在于使用的是标准C++库的文件操作函数,而不是Linux系统调用。具体来说,程序使用`std::ifstream`来打开目录,使用`std::getline()`逐行读取目录项,使用`stat()`获取每个目录项的文件状态。根据文件状态的`st_mode`成员,可以判断一个目录项是文件还是目录。如果是目录,递归调用`traverseDir()`函数遍历它。如果是文件,输出文件路径。注意,程序跳过了所有以`.`开头的文件目录,因为它们通常被认为是隐藏文件目录
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值