Rename All Files
Write a program that retrieves all files in a specified directory, sorts them by their size in ascending order, and renames them to file_1, file_2, etc., according to their order. The program should ensure that only regular files (not directories) are renamed.
Hint
- Use the
<filesystem>library to work with files and directories. - Define a custom struct to conveniently store the file path and size.
- Use
std::vectorto store these structs. - Use
std::sortto order the files (or custom file structs) by size. - Rename files using
std::filesystem::rename.
Answer
#include <iostream>
#include <filesystem>
#include <vector>
#include <algorithm>
struct FileInfo {
std::filesystem::path filePath;
uintmax_t fileSize;
FileInfo(const std::filesystem::path& path, uintmax_t size) : filePath(path), fileSize(size) {}
};
int main() {
std::string directoryPath;
std::cout << "Enter the path to the directory: ";
std::cin >> directoryPath;
// Vector to store FileInfo structs
std::vector<FileInfo> files;
// Iterate through the directory and gather regular files and their sizes
for (const auto& entry : std::filesystem::directory_iterator(directoryPath)) {
if (std::filesystem::is_regular_file(entry.path())) {
files.push_back(FileInfo(entry.path(), std::filesystem::file_size(entry.path())));
}
}
// Sort the files by size
std::sort(files.begin(), files.end(),
[](const FileInfo& a, const FileInfo& b) {
return a.fileSize < b.fileSize;
});
// Rename files in order using indexed loop
for (int i = 0; i < files.size(); i++) {
std::filesystem::path newFileName = directoryPath + "/file_" + std::to_string(i + 1);
std::filesystem::rename(files[i].filePath, newFileName);
}
std::cout << "Files have been renamed based on their size." << std::endl;
return 0;
}