trainings/AdvancedCppV2/Presentation/exercises/files/main.cpp

74 lines
3.2 KiB
C++

#include <filesystem>
#include <iostream>
#include <vector>
#include <algorithm>
namespace fs = std::filesystem;
void printPerms(fs::perms p) {
std::cout << ((p & fs::perms::owner_read) != fs::perms::none ? "r" : "-")
<< ((p & fs::perms::owner_write) != fs::perms::none ? "w" : "-")
<< ((p & fs::perms::owner_exec) != fs::perms::none ? "x" : "-")
<< ((p & fs::perms::group_read) != fs::perms::none ? "r" : "-")
<< ((p & fs::perms::group_write) != fs::perms::none ? "w" : "-")
<< ((p & fs::perms::group_exec) != fs::perms::none ? "x" : "-")
<< ((p & fs::perms::others_read) != fs::perms::none ? "r" : "-")
<< ((p & fs::perms::others_write) != fs::perms::none ? "w" : "-")
<< ((p & fs::perms::others_exec) != fs::perms::none ? "x" : "-")
<< '\n';
}
void printPermissionsForDir() {
for (const auto& entry : fs::directory_iterator(fs::current_path().string() + "/project")) {
if (fs::is_regular_file(entry.path())) {
std::cout << "File: "
<< std::left << std::setw(20)
<< entry.path().filename()
<< " | Permissions: ";
printPerms(fs::status(entry.path()).permissions());
}
}
std::cout << std::string(80, '_') << "\n\n";
}
void changePermissions() {
for (const auto& entry : fs::directory_iterator(fs::current_path().string() + "/project")) {
if (fs::is_regular_file(entry.path())) {
fs::perms p = fs::perms::none;
using per = fs::perms;
if(entry.path().extension() == ".exe"){
p = per::owner_all | per::group_read | per::group_write | per::others_read | per::others_write;
} else if(entry.path().extension() == ".cpp" || entry.path().extension() == ".hpp"){
p = per::owner_read | per::owner_write | per::group_read | per::others_read;
}
fs::permissions(entry.path(), p);
}
}
}
int main() {
printPermissionsForDir();
changePermissions();
printPermissionsForDir();
// Part 2 unncoment later
auto print_last_write_time = [](std::filesystem::file_time_type const& ftime) {
std::time_t time = std::chrono::system_clock::to_time_t(
std::chrono::file_clock::to_sys(ftime));
std::cout << "File write time is " << std::asctime(std::localtime(&time));
};
std::vector<std::pair<fs::path, fs::file_time_type>> paths;
for (const auto& entry : fs::directory_iterator(fs::current_path().string() + "/project")) {
if (fs::is_regular_file(entry.path())) {
paths.push_back(std::make_pair(entry.path(), fs::last_write_time(entry.path())));
}
}
std::sort(paths.begin(), paths.end(), [](auto a, auto b) {return ( a > b );});
std::cout << "Last modified file is: " << paths.front().first << '\n';
print_last_write_time(std::filesystem::last_write_time(paths.front().first));
std::cout << "files which were longest unmodified: " << paths.back().first << std::endl;
print_last_write_time(std::filesystem::last_write_time(paths.back().first));
}