Linux系统C++获取目录中文件信息的代码实现

这是一个用于获取指定目录下所有文件信息的C++代码,适用于Linux系统。以下是实现流程:

  1. 使用库中的opendir函数打开目录。
  2. 使用readdir函数读取目录中的每个文件。
  3. 利用stat函数获取文件的详细信息(例如:大小、权限、修改时间等)。
  4. 最后,关闭目录并处理文件信息。

示例代码如下:

#include 
#include 
#include 
#include 

void listFiles(const char* dirPath) {
    DIR* dir = opendir(dirPath);
    if (dir == nullptr) {
        std::cerr << "Error opening directory" << std xss=removed xss=removed>d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
            continue;
        struct stat fileStat;
        std::string filePath = std::string(dirPath) + "/" + entry->d_name;
        if (stat(filePath.c_str(), &fileStat) == 0) {
            std::cout << "File: " << entry>d_name << " Size: " << fileStat path = "/your/directory/path">

通过以上代码,你可以轻松遍历指定目录,并获取每个文件的相关信息。

txt 文件大小:813B