These files can be used in any way you like.
We provide no warranty whatsoever.
HEADER
#ifndef FILE_H
#define FILE_H
#include <vector>
#include <string>
class File{
public:
File(std::string);
File(char*);
std::vector<File> getList();
bool isDir();
bool isFile();
bool Exists();
std::string getName();
private:
void whatAmI();
std::vector<File> children;
std::string name;
bool isdir;
bool isfile;
bool exists;
};
#endif
SOURCEFILE
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
File::File(std::string nm): name(nm), isdir(false), exists(false), isfile(false) {whatAmI();}
File::File(char* nm): name(nm), isdir(false), exists(false), isfile(false) {whatAmI();}
std::vector<File> File::getList()
{
if(isdir){
DIR *dir;
struct dirent *ent;
if ((dir = opendir(name.c_str())) == 0){
printf("Unable to open directory %s", name.c_str());
}
while ((ent = readdir(dir)) != NULL){
children.push_back(name + "/" + ent->d_name);
}
if (closedir(dir) != 0){
printf("Unable to close directory %s", name.c_str());
}
}
return children;
}
bool File::isDir()
{
return isdir;
}
bool File::isFile()
{
return isfile;
}
bool File::Exists()
{
return exists;
}
void File::whatAmI()
{
FILE* tempfile;
DIR* tempdir;
// test for directory
if ((tempdir = opendir(name.c_str())) != 0){
isdir = exists = true;
closedir(tempdir);
}
// test for file
else if ((tempfile = fopen(name.c_str(), "r")) != 0){
isfile = exists = true; // is a file implicitly by not being a dir
fclose(tempfile);
}
// neither file nor directory
else {
exists = false;
name.empty();
}
}
std::string File::getName(){
return name;
}
EXAMPLE MAIN
#include <stdlib.h>
#include "file.h"
using namespace std;
int main(int argc, char *argv[])
{
File dir("c:/temp/");
std::vector<File> templist = dir.getList();
printf("File properties:\n");
printf("Exists:\t\t%s\n", dir.Exists()?"Yes":"No");
printf("File:\t\t%s\n", dir.isFile()?"Yes":"No");
printf("Directory:\t%s\n\n", dir.isDir()?"Yes":"No");
if(dir.isDir()){
printf("Childs:\n");
for(int x = 0; x < templist.size(); x++){
printf("%s\t%s\n", templist[x].isDir()?"dir":"file", templist[x].getName().c_str());
}
}
system("PAUSE");
return 0;
}