#include <iostream>
#include <string>
#include <vector>
#include <dirent.h>
#include <string.h>
#include <stack>
#include <sys/stat.h>
uint64_t GetFileSize(const std::string& filepath)
{
struct stat statbuf;
stat(filepath.c_str(), &statbuf);
return statbuf.st_size;
}
std::vector<std::string> get_all_files_in_directory(const std::string& directory)
{
std::vector<std::string> file_paths;
DIR* dir = opendir(directory.c_str());
if (dir == nullptr)
{
std::cerr << "无法打开目录: " << directory << std::endl;
return file_paths;
}
struct dirent* dirEntry;
while ((dirEntry = readdir(dir)) != nullptr)
{
if (dirEntry->d_type == DT_REG)
{
std::string file_path = directory + "/" + dirEntry->d_name;
file_paths.push_back(file_path);
}
else if (dirEntry->d_type == DT_DIR && strcmp(dirEntry->d_name, ".")!=0 && strcmp(dirEntry->d_name, "..")!=0 )
{
std::vector<std::string> sub_file_paths = get_all_files_in_directory(directory+"/"+dirEntry->d_name);
file_paths.insert(file_paths.end(), sub_file_paths.begin(), sub_file_paths.end());
}
}
closedir(dir);
return file_paths;
}
std::vector<std::string> GetAllFilesInDirectory(const std::string& directory)
{
uint64_t totalSize = 4096;
std::vector<std::string> file_paths;
std::stack<std::string> dirs;
DIR* dir = opendir(directory.c_str());
if(dir == nullptr)
{
std::cerr << "无法打开目录: " << directory << std::endl;
return file_paths;
}
dirs.push(directory);
while(!dirs.empty())
{
std::string currentDir = dirs.top();
dirs.pop();
DIR* sub_dir = opendir(currentDir.c_str());
if(sub_dir == nullptr)
{
std::cerr << "无法打开子目录: " << currentDir << std::endl;
continue;
}
struct dirent* dirEntry;
while((dirEntry = readdir(sub_dir)) != nullptr)
{
if(dirEntry->d_type == DT_REG)
{
std::string file_path = currentDir + "/" + dirEntry->d_name;
file_paths.push_back(file_path);
totalSize += GetFileSize(file_path);
}
else if(dirEntry->d_type == DT_DIR && strcmp(dirEntry->d_name, ".")!=0 && strcmp(dirEntry->d_name, "..")!=0 )
{
std::string subDir = currentDir + "/" + dirEntry->d_name;
dirs.push(subDir);
totalSize += 4096;
}
}
closedir(sub_dir);
}
closedir(dir);
std::cout << "totalSize = " << totalSize <<std::endl;
return file_paths;
}
int main()
{
std::string directory = "/home/wang/downloads/loglog";
std::vector<std::string> dirFilePath;
std::vector<std::string> file_paths1 = GetAllFilesInDirectory(directory);
std::vector<std::string> file_paths2 = get_all_files_in_directory(directory);
uint64_t size1 = 0;
for (const auto& file_path : file_paths1)
{
std::cout << file_path << std::endl;
size1 += GetFileSize(file_path);
}
uint64_t size2 = 0;
for (const auto& file_path : file_paths2)
{
std::cout << file_path << std::endl;
size2 += GetFileSize(file_path);
}
std::cout << "size1 = " << size1 << std::endl;
std::cout << "size2 = " << size2 << std::endl;
std::cout << std::endl;
std::cout << std::endl;
std::cout << "file_paths1.size = " << file_paths1.size() << std::endl;
std::cout << "file_paths2.size = " << file_paths2.size() << std::endl;
return 0;
}