Created
December 14, 2015 23:26
-
-
Save colltoaction/5d85a8b3716a788cbdd8 to your computer and use it in GitHub Desktop.
A simple C++ class that reads files in a directory, and also works as an example of RAII.
This file contains 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
#include "DirectoryException.h" | |
DirectoryException::DirectoryException(const std::string& what_arg) | |
: std::logic_error(what_arg) { | |
} |
This file contains 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
#ifndef DIRECTORYEXCEPTION_H | |
#define DIRECTORYEXCEPTION_H | |
#include <stdexcept> | |
class DirectoryException : public std::logic_error { | |
public: | |
explicit DirectoryException(const std::string& what_arg); | |
}; | |
#endif // DIRECTORYEXCEPTION_H |
This file contains 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
#include "DirectoryException.h" | |
#include "DirectoryReader.h" | |
DirectoryReader::DirectoryReader(std::string path) | |
: dir_(opendir(path.c_str())) { | |
if (dir_ == NULL) { | |
throw DirectoryException("Can't open directory"); | |
} | |
} | |
DirectoryReader::~DirectoryReader() { | |
closedir(dir_); | |
} | |
std::vector<std::string> DirectoryReader::files() const { | |
std::vector<std::string> files; | |
struct dirent *ent; | |
while ((ent = readdir(dir_)) != NULL) { | |
if (ent->d_type == DT_REG) { // regular file | |
files.push_back(ent->d_name); | |
} | |
} | |
return files; | |
} |
This file contains 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
#ifndef DIRECTORYREADER_H | |
#define DIRECTORYREADER_H | |
#include <dirent.h> | |
#include <vector> | |
class DirectoryReader { | |
public: | |
explicit DirectoryReader(std::string path); | |
~DirectoryReader(); | |
std::vector<std::string> files() const; | |
private: | |
DIR *dir_; | |
}; | |
#endif // DIRECTORYREADER_H |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment