C++ gives you provisions for file interaction.
I will show you my FileReader class which employs a bit of C style file handling using C++.
// BEGIN HEADER
#include <stdio.h>
#include <exception>
#include <stdexcept>
#define DISALLOW_COPY(type) \
type(const type&); \
void operator=(const type&)
class FileReader { // RAII applies to file contents
FILE *file; // c-style open/close
DISALLOW_COPY(FileReader);
protected:
unsigned char *data; // local copy
long size;
public:
FileReader(const char *filename);
~FileReader();
unsigned long getSize();
unsigned char *getFileData();
};
// END HEADER
FileReader::FileReader(const char *filename) {
file = NULL; data = NULL;
if (!(file = fopen(filename, "rb"))) { throw std::runtime_error(std::string("File could not be opened: ")+filename); }
fseek(file,0,SEEK_END);
size = ftell(file);
rewind(file);
data = new unsigned char [size];
VERIFY(size == (long)fread(data, 1, size, file)); // debug macro (just ignore it)
fclose(file);
#ifdef DEBUG
PRINT("FileReader opening file "); printf("%s, %ld bytes.\n",filename,size);
#endif
}
FileReader::~FileReader() {
delete[] data;
}
unsigned char *FileReader::getFileData() { return data; }
unsigned long FileReader::getSize() { return size; }
I will note that you probably want to avoid using C++ to list files in the directory if you can. Why can you not simply assume whether or not certain files will be there or not be there? I've done a bit of game programming and pretty much the only times you need to worry about the filesystem are for logging purposes or for loading assets. For both of these you can pretty much just assume what their paths are.
In addition, you may want to look at the remove function for deleting files. I can't come up with any raw code in C++ for performing the task that ls
is meant for. I wouldn't use C++ to do such a task (hint: ls
is a pretty neat program).
Also take a look at stat
and opendir
(thanks Ben) which should be available on your platforms. Another point to make is that a task such as listing files in a dir are generally things you're gonna want to ask your OS kernel to do for you.
A more high-level approach mentioned by another answerer is Boost Filesystem, which is a solid choice as Boost usually is: Take a look at this directory iteration example.
From a game programming perspective I've tended to lean on stuff like Lua's os()
. For example if you have a Python program you could just do something like os.system("ls")
to get your dir contents assuming you have an ls
program available.
You could also exec
the ls
program from your C++ program.