I do not want to call this a wrapper, but no other name comes to mind right now, so I'll use it incorrectly for the rest of the question - It's just a class that adds C++ functions to dirent.h
but it's very specific to my use case.
All of the code works well, but I've never worked with the dirent.h
library and jumping right into a C++ wrapper is something, so I'm really insecure about it's performance and memory usage in practical scenarios.
~But, of course please also judge the readability - I want to know if I should add comments or if my naming scheme and layout is self explanatory.
Quick Description
I'm working on C++ based file manager that needs functions that return vectors of whole directories, of course, that it can display it in one loop. It will also need some more info (metadata I guess), like it's type so it can do all the fancy color syntax.
Here is the final version so far (with some debug code):
inode.h
#ifndef INODECLASS
#define INODECLASS
#include <dirent.h>
#include <string.h>
#include <iostream>
#include <vector>
#include <string>
class Inode
{
public:
struct InodeMeta {
std::string name;
std::string path;
unsigned char type;
};
private:
std::string pwd_path_;
std::vector<InodeMeta *> buffer_;
public:
Inode(const std::string &);
~Inode();
void ClearBuffer();
bool ReloadBuffer(const std::string &);
std::vector<InodeMeta> DumpBuffer(const std::string &);
};
#endif
inode.cc
#include "inode.h"
Inode::Inode(const std::string &arg_path = ".") {
if ( !ReloadBuffer(arg_path) )
ClearBuffer();
}
Inode::~Inode() {
ClearBuffer();
}
void Inode::ClearBuffer() {
for (auto &item : buffer_)
delete item;
buffer_.clear();
}
bool Inode::ReloadBuffer(const std::string &arg_path = "") {
if (arg_path.length() != 0) pwd_path_ = arg_path;
DIR *dirstream;
dirent *diritem;
ClearBuffer();
if ( (dirstream = opendir(pwd_path_.c_str())) != NULL )
{
while ( (diritem = readdir(dirstream)) != NULL ) {
if ( strcmp(diritem->d_name, ".") != 0 &&
strcmp(diritem->d_name, "..") != 0 )
buffer_.emplace_back( new InodeMeta{ std::string(diritem->d_name),
std::string(pwd_path_) + "/" + std::string(diritem->d_name),
diritem->d_type} );
}
closedir(dirstream);
}
else return false;
return true;
}
std::vector<Inode::InodeMeta> Inode::DumpBuffer(const std::string &arg_path = "") {
if (arg_path.length() != 0) ReloadBuffer(arg_path);
std::vector<InodeMeta> ret_list;
for (auto &item : buffer_)
ret_list.push_back(*item);
return ret_list;
}
//DEBUG ONLY//
#include <iostream>
int main() {
Inode I;
std::vector<Inode::InodeMeta> inodelist = I.DumpBuffer();
for (auto &item : inodelist)
std::cout << item.name << " ; " << item.path << '\n';
I.ReloadBuffer("/tmp/");
inodelist.clear();
inodelist = I.DumpBuffer();
for (auto &item : inodelist)
std::cout << item.name << " ; " << item.path << '\n';
}
Just in case you either want to see the whole project (I started it like 3 days ago, don't judge me too hard), or just make a quick git clone
and test it yourself here.
dev
branch. \$\endgroup\$