-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathfiles.cpp
94 lines (75 loc) · 2.39 KB
/
files.cpp
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// Grayson Pike, 2018
#include "files.hpp"
#include <iostream>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
/*
Returns a vector of strings representing the directories within a given path
Strings are directory names, not full paths
*/
std::vector<std::string> get_directories(std::string path) {
std::vector<std::string> result;
DIR *dir = opendir(path.c_str());
struct dirent *entry = readdir(dir);
while (entry != NULL)
{
// Only add directories to list, not files
// Ignore . and .. as directory listings
if (entry->d_type == DT_DIR && strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) {
result.push_back(entry->d_name);
}
entry = readdir(dir);
}
closedir(dir);
return result;
}
/*
Returns a vector of strings representing the files within a given path
Strings are filenames, not full paths
*/
std::vector<std::string> get_files(std::string path) {
std::vector<std::string> result;
DIR *dir = opendir(path.c_str());
struct dirent *entry = readdir(dir);
while (entry != NULL)
{
// Only add directories to list, not files
// Ignore . and .. as directory listings
if (entry->d_type == DT_REG && strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) {
result.push_back(entry->d_name);
}
entry = readdir(dir);
}
closedir(dir);
return result;
}
/*
Create a directory if it doesn't already exist
Doesn't create intermediate directories, nested directories will need to be created one at a time
Returns true on success, false otherwise.
*/
bool create_directory(std::string path, bool silent) {
if (mkdir(path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) == -1) {
if(!silent) {
std::cerr << "Error creating directory '" << path << "'. Does it already exist?" << std::endl;
}
return false;
}
return true;
}
/*
Save an image in PGM format with a given path/filename
Returns true on success, false otherwise
*/
bool save_pgm_image(cv::Mat image, std::string filepath) {
// Save cropped image to file
try {
cv::imwrite(filepath, image);
}
catch (std::runtime_error& ex) {
std::cerr << "Exception saving image to PGM format: " << ex.what() << std::endl;
return false;
}
return true;
}