我有一个任务,我需要浏览文件夹中的所有文件。对于每个文件,我需要知道每个唯一文件扩展名,每个唯一文件扩展名有多少个文件以及每个唯一文件扩展名的总大小。我必须能够使用文件扩展名或文件扩展名的总大小对此进行排序。我想用的第一件事是一张地图。这将跟踪每个唯一的文件扩展名和文件扩展名被发现的次数。我现在如何将文件扩展名的总大小关联到我的地图?因此,例如我需要的输出是这样的:具有两个键值的映射
使用文件扩展名排序 的.cpp:1:3400 .EXE:3:3455600 .MP4:25:200000404
使用总文件。扩展大小排序 .MP4:25:200000404 .EXE:3:3455600 的.cpp:1:3400
这里是我的代码一定的编辑之后有:
#include <iostream>
#include <filesystem>
#include <map>
using namespace std;
using namespace std::tr2::sys;
class fileInfo {
public:
int fileCount;
long long fileSize;
};
void scan(path f)
{
map<string, fileInfo> fileMap;
cout << "Scanning = " << system_complete(f) << endl;
directory_iterator d(f);
directory_iterator e;
for(; d != e; ++d)
{
path p = d->path();
cout << "\nExtension is: " << extension(p) << "\tFile size is: " << file_size(p) << endl;
fileMap[extension(p)].fileCount ++;
fileMap[extension(p)].fileSize += file_size(p);
}
for (map<string, fileInfo>::iterator it = fileMap.begin(); it != fileMap.end(); ++it)
{
cout << it->first << " : " << it->second.fileCount << " : " << it->second.fileSize << endl;
}
}
int main(int argc, char* argv[])
{
path folder = "..";
scan(folder);
return 0;
}
编辑:所以我已经实现了类fileInfo。这是有点工作。但我遇到了file_size问题。通过循环第一次运行时,它正确返回FILE_SIZE后,但通过循环FILE_SIZE隔日运行将返回0。
我该如何填充地图? – DHines
使用运算符[]或插入方法 – gerrytan
这是我试过的,不知道我是否以正确的方式去解决这个问题... class extStat { public: \t int fileCount_; \t int fileSize_; }; void scan(path f) { \t extStat ext; \t map map; \t cout <<“Scanning =”<< system_complete(f)<< endl; \t directory_iterator d(f); \t directory_iterator e; (; d!= e; ++ d) \t \t { \t \t path p = d-> path(); \t \t int temp = file_size(p); \t \t ext.fileCount _ ++; \t \t ext.fileSize_ + = temp; \t \t map [extension(p)] ext; \t} } –
DHines