2

in the directory containing my exe I have a folder called "saves". I want to display the files this directory contains.

I used the code found here: Listing directory contents using C and Windows

Now the tricky part. if I use .\\saves\\ as my directory it tells me that the path could not be found. However if I use ..\\release\\saves\\ it works fine. But that's stupid. I don't want to go to the parent folder and than go back. Especially regarding that I don't know what name the user gives to the directory containing the exe (in my case it's "release" but who knows what the user does :-D).

I read through this: http://msdn.microsoft.com/en-us/library/aa365247(v=vs.85).aspx#fully_qualified_vs._relative_paths but it didn't help very much.

I also tried saves\\ or .\saves\\ but it doesn't work either.

I hope somebody can tell me how to fix this.

Zoe
  • 27,060
  • 21
  • 118
  • 148
Kilian Laudt
  • 21
  • 1
  • 2

4 Answers4

3

You're actually doing nothing wrong in code -- you've been launching the project from Visual Studio, which sets the Working Directory to the parent of the Release/Debug folders.

Go to Project->Settings(Properties)->Configuration Properties->Debugging->Working Directory

You can also run the exe outside of VS and the relative paths will behave like you expect.

user1054922
  • 2,101
  • 2
  • 23
  • 37
2

If it is relative from the path to the executable, and not from the path of the current working directory, you could use GetModuleFileName() to obtain the full path to the executable. Then, remove the name of the executable from the end of the path and build the paths using that:

std::string executable_directory_path()
{
    std::vector<char> full_path_exe(MAX_PATH);

    for (;;)
    {
        const DWORD result = GetModuleFileName(NULL,
                                               &full_path_exe[0],
                                               full_path_exe.size());

        if (result == 0)
        {
            // Report failure to caller.
        }
        else if (full_path_exe.size() == result)
        {
            // Buffer too small: increase size.
            full_path_exe.resize(full_path_exe.size() * 2);
        }
        else
        {
            // Success.
            break;
        }
    } 

    // Remove executable name.
    std::string result(full_path_exe.begin(), full_path_exe.end());
    std::string::size_type i = result.find_last_of("\\/");
    if (std::string::npos != i) result.erase(i);

    return result;
}
hmjd
  • 120,187
  • 20
  • 207
  • 252
0

I think your mistake was using \\saves\\and forgeting to specify a search parameter/string
You should use:

saves\\*

this will search for any file or folder

0

I would use boost::filesystem http://www.boost.org/doc/libs/1_53_0/libs/filesystem/doc/index.htm.

As a bonus you will get operating system independent code.

AxelOmega
  • 974
  • 10
  • 18