Hey everyone need help on a project im doing in c++, so far I have made a command interpreter, that breaks user input into array of Strings sepperated by spaces and have a run function. Now I am trying to do the list() and list(directory) but I'm not quite sure how to in c++. The python code for it is as follows:

os.path.exists(path) Returns true if path exists.

os.listdir(path) returns a python list of contents of directory.

os.getcwd() Returns the path of current directory.

I would just like the equivalent function that would work in c++, Thank you for any suggestions

Recommended Answers

All 3 Replies

Are you using *nix or MS-Windows, how to get the folder contents depends on the os you are using. I have written a code snippet for each. boost has library that is os independent. Which ever you use it will not be as simple as it was in python.

_getcwd() is a win32 api function. Not sure the replacement for *nix

There is no similar function to os.path.exists. Instead, you can call stat() to see if the path exists. stat() will return an error is no such path or file.

_getcwd() is a win32 api function. Not sure the replacement for *nix

getcwd() in <unistd.h>. ;) For processing the contents of a directory, you'd probably end up using opendir(), readdir(), and closedir():

DIR *dir = opendir(".");

if (dir) {
    struct dirent *info;

    while ((info = readdir(dir))) {
        cout << info->d_name << '\n';
    }

    closedir(dir);
}

The Windows equivalent would use FindFirstFile(), FindNextFile(), and FindClose():

WIN32_FIND_DATA info;
HANDLE h = FindFirstFile(".", &info);

if (h != INVALID_HANDLE_VALUE) {
    do {
        cout << info.cFileName << '\n';
    } while (FindNextFile(h, &info));

    FindClose(h);
}

That information could be gleaned from AD's links, but the above boils it down to the core operations.

I'll give this a shot, ill let you know how it goes. thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.