Jul 27, 2013 at 9:54pm UTC
i was looking for a method to define a function upon success of an include, and define that same function another way upon failing of that include.
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
#include <iostream>
#include <string>
#include <vector>
#include <dirent.h>
#include <cerrno>
int getdir (std::string dir, std::vector<std::string> &files){
DIR *dp;
struct dirent *dirp;
if ((dp = opendir(dir.c_str())) == NULL) {
std::cout << "Error(" << errno << ") opening " << dir << std::endl;
return errno;
}
while ((dirp = readdir(dp)) != NULL) {
files.push_back(std::string(dirp->d_name));
}
closedir(dp);
return 0;
}
int main(){
}
more specifically
I was looking for a way to say:
if including dirent.h succeeds, define getdir as above, else define getdir to return a string stating that it failed to include , and continue on with program
Last edited on Jul 27, 2013 at 9:54pm UTC
Jul 27, 2013 at 10:17pm UTC
find out the include guards for dirent.h and then write directly above get dir
#ifdef _what_ever_the_include_guard_is
then at the end of the function #endif
Jul 27, 2013 at 10:35pm UTC
Last edited on Jul 27, 2013 at 10:37pm UTC
Jul 27, 2013 at 10:38pm UTC
@DTSCode I don't believe that will work, if the compiler can't find the header it will throw an error.
@metulburr
My suggestion is to use Boost.Filesystem.
Edit: Here is an untested example that
should do what your code does using boost.
1 2 3 4 5 6 7 8 9 10 11 12
#include <boost/filesystem.hpp>
int getdir (std::string dir, std::vector<std::string> &files){
using namespace boost::filesystem;
path p(dir);
directory_iterator endit;
if (exists(p) && is_directory(p))
{
for (directory_iterator dit(p); dit != endit; ++dit)
files.push_back(dit->string());
}
}
Last edited on Jul 28, 2013 at 4:22am UTC