我需要从目录中输出 5 个最大的文件。为此,我使用了一个 boost 文件系统 c++。在写程序的过程中,我遇到了困难。我可以输出目录中的所有文件、文件大小、文件创建日期和文件属性。在 vector 中我放了文件名,但我就是不知道如何按大小排序。我需要从指定目录输出 5 个最大的文件。我认为您必须首先按文件大小降序排序。也就是从大值到小值。然后不需要扫描。它很可能需要在循环中完成。请帮助我。
#define _CRT_SECURE_NO_WARNINGS
#include <Windows.h>
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <boost/filesystem.hpp>
using namespace std;
using namespace boost::filesystem;
void ShowAttributes(DWORD attributes);
void AttribFile(const char* str);
void Attrib();
int main(int argc, char* argv[])
{
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
if (argc < 2)
{
cout << "Using Name Directory" << endl;
return 1;
}
path Part(argv[1]);
try
{
if (exists(Part))
{
if (is_regular_file(Part))
{
cout << Part << " Size " << file_size(Part) << " bytes ";
time_t Time = last_write_time(Part);
cout << asctime(localtime(&Time)) << endl;
}
else if (is_directory(Part))
{
cout << "Directory " << Part << " include:" << endl;
vector<string> vecList;
for (auto j : directory_iterator(Part))
vecList.push_back(j.path().filename().string());
sort(vecList.begin(), vecList.end());
string filePath;
for (auto i : vecList)
{
cout << " " << i;
filePath = Part.parent_path().string() + "/" + i;
if (is_regular_file(filePath))
{
if (Is_Executable_File(filePath))
cout << "*";
cout << " Size " << file_size(filePath) << " bytes ";
time_t Time = last_write_time(Part);
cout << asctime(localtime(&Time)) << endl;
AttribFile(filePath.c_str());
}
cout << endl;
}
}
}
else
cout << Part << " Erroe!" << endl;
}
catch (const filesystem_error& ex)
{
cout << ex.what() << endl;
}
return 0;
}
void ShowAttributes(DWORD attributes)
{
if (attributes & FILE_ATTRIBUTE_ARCHIVE)
cout << " archive" << endl;
if (attributes & FILE_ATTRIBUTE_DIRECTORY)
cout << " directory" << endl;
if (attributes & FILE_ATTRIBUTE_HIDDEN)
cout << " hidden" << endl;
if (attributes & FILE_ATTRIBUTE_NORMAL)
cout << " normal" << endl;
if (attributes & FILE_ATTRIBUTE_READONLY)
cout << " read only" << endl;
if (attributes & FILE_ATTRIBUTE_SYSTEM)
cout << " system" << endl;
if (attributes & FILE_ATTRIBUTE_TEMPORARY)
cout << " temporary" << endl;
}
void AttribFile(const char* str)
{
DWORD attributes;
attributes = GetFileAttributesA(str);
ShowAttributes(attributes);
}
void Attrib()
{
char filename[MAX_PATH];
DWORD attributes;
cout << "Name of file: ";
cin >> filename;
attributes = GetFileAttributesA(filename);
ShowAttributes(attributes);
}
最佳答案
创建一个类或结构来保存每个文件所需的信息,例如
struct MyFile
{
std::string name;
size_t size;
}
创建一个 vector 并从您的文件夹中读取所有文件
然后对 vector 进行排序并给出自定义比较(例如以 lambda 的形式),参见 Sorting a vector of custom objects有关详细信息
关于c++ - 如何按文件大小降序对文件进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50318372/