Modern C++ idoms and recipes

meshell
199 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

Filesystem library

An important addition to the C++17 standard is the filesystem library. The filesystem library is based on boost::filesystem and enables us to work with paths, files and directories.

The current compilers (gcc 7.2. is used for this exercise) provide an implementation of the library in the std::experimental::filesystem namespace and the actual header is <experimental/filesystem>.

Implement a program that searchs in the 'data' directory of the current directory for all files which contain 'copy' in its content and copy them to a new folder 'data_new'.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <experimental/filesystem>
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
namespace fs = std::experimental::filesystem;
using namespace std::string_literals;
/**
* List all regular files in a directory
* @param dir directory path
* @return vector of paths of regular files in directory
*/
std::vector<fs::path> list_regular_files_in_directory(const fs::path& dir) {
std::vector<fs::path> regular_files;
if (fs::exists(dir) && fs::is_directory(dir)) {
for (const auto& entry : fs::directory_iterator(dir)) {
if (fs::is_regular_file(entry.status())) {
regular_files.emplace_back(entry.path());
}
}
}
return regular_files;
}
/**
* Check if a file contains a particular string
* @param filepath path to the file that should be checked
* @param str string to search for in file
* @retval true if the string str was found in file filepath
* @retval false otherwise
*/
bool file_contains_string(const fs::path& filepath, const std::string& str) {
if (fs::exists(filepath)) {
std::ifstream file(filepath);
std::string line;
while (getline(file, line)) {
if (line.find(str) != std::string::npos) {
return true;
}
}
}
return false;
}
int main() {
// TODO search in the 'data' directory of the current directory for all files
// which contain 'copy' in its content and copy them to a new folder 'data_new'.
return 0;
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content