Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A simple C++ class that reads files in a directory, and also works as an example of RAII.
#include "DirectoryException.h"
DirectoryException::DirectoryException(const std::string& what_arg)
: std::logic_error(what_arg) {
}
#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
#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;
}
#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
You can’t perform that action at this time.