Last active
October 22, 2022 17:00
-
-
Save mshafae/f6a5ebf19ad736a3bdcf28be34b84cc4 to your computer and use it in GitHub Desktop.
CPSC 120 Demonstrate how to use the filesystem library and functions to find files and rename them.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Gist https://gist.github.com/f6a5ebf19ad736a3bdcf28be34b84cc4 | |
// To try out this program, you don't need to have a folder full of JPEG images. | |
// Do the following from from the command line to create some sample data to | |
// demonstrate how this program works. | |
// $ mkdir sample_data | |
// $ cd sample_data | |
// $ touch blue.jpeg red.jpeg yellow.jpeg orange.jpeg green.jpeg purple.jpeg | |
// $ cd .. | |
// $ clang++ -std=c++17 cpsc120_rename_jpeg.cc | |
// $ ./a.out sample_data | |
// $ ls sample_data | |
#include <filesystem> | |
#include <iostream> | |
#include <string> | |
#include <vector> | |
// Given path_string, find the last occurance of base and return the substring | |
// from the start to the base. For example, given Basename("foo.jpg", ".jpg") | |
// the function shall return "foo". | |
std::string Basename(const std::string& path_string, const std::string& base) { | |
return path_string.substr(0, | |
path_string.find_last_of(base) - base.size() + 1); | |
} | |
// Given a path_string, return true if the path_string ends with ext, else | |
// false. | |
bool HasExtension(const std::string& path_string, const std::string& ext) { | |
return path_string.substr(path_string.size() - ext.size()) == ext; | |
} | |
int main(int argc, char const* argv[]) { | |
std::vector<std::string> args{argv, argv + argc}; | |
if (args.size() < 2) { | |
std::cout << "Please provide a path to a directory.\n"; | |
return 1; | |
} | |
std::filesystem::path input_directory{args.at(1)}; | |
if (!std::filesystem::is_directory(input_directory)) { | |
std::cout << input_directory << " is not a directory.\n"; | |
std::cout << "Please provide a path to a directory.\n"; | |
return 1; | |
} | |
std::vector<std::string> jpeg_file_list; | |
std::string wrong_extension{".jpeg"}; | |
std::string correct_extension{".jpg"}; | |
for (const auto& fs_item : | |
std::filesystem::directory_iterator(input_directory)) { | |
if (fs_item.is_regular_file() and | |
HasExtension(fs_item.path().string(), wrong_extension)) { | |
std::string base_file_name = | |
Basename(fs_item.path().string(), wrong_extension); | |
std::filesystem::path renamed_file_path{base_file_name + | |
correct_extension}; | |
std::cout << "Renaming " << fs_item.path().string() << " to " | |
<< renamed_file_path.string() << "\n"; | |
std::filesystem::rename(fs_item, renamed_file_path); | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment