I need to make this header that can find file names from a directory for a school project though it is important to mention that my teacher is very strict and i'm not allowed to use libraries that are already made (dirent.h, boost etc). To put it simply, i have to make it from scratch.
The only 2 functions i'm actually allowed to use are
// They more test accesibility rather than actual existance but it is enough
// LPCSTR = constant long pointer to string
// similar to: char* pathToFile
bool DoesFileExist(LPCSTR pathToFile)
{
std::ifstream file(pathToFile);
return file.good();
}
bool DoesDirExist(LPCSTR pathToDir)
{
DWORD dwAttrib = GetFileAttributes(pathToDir);
return (dwAttrib != INVALID_FILE_ATTRIBUTES && (dwAttrib & FILE_ATTRIBUTE_DIRECTORY));
}
I tought a recursive function will work best if i just needed to print the names. This is how the code should act like.
void PrintSubfiles(LPCSTR CurrentDirectory)
{
CHAR pathToSomething[MAX_PATH];
// this is where the string takes the path of either a file or a directory
// I imagined the principle of the GetNextPath() function similar to strtok()
GetNextPath(CurrentDirectory,pathToSomething);
while (pathToSomething != NULL)
{
if (DoesDirExist(pathToSomething))
{
// print the name of this directory and enter it
std::cout<<"IN DIRECTORY: "<<pathToSomething<<std::endl;
PrintSubFiles(pathToSomething);
}
if (DoesFileExist(pathToSomething))
{
// print the file name
std::cout<<"FILE: "<<pathToSomething<<std::endl;
}
GetNextPath(NULL,pathToSomething);
}
}
I actually have no idea how to implement the GetNextPath()
function. It doesen't need to be super fast or memory efficient. I just need to get the data to that pathToSomething
string. Any idea how to do it without those libraries ?
EDIT: This header is specifically for windows. No need for portable solutions.