views:

115

answers:

2
C:\Projects\Logs\RTC\MNH\Debug  
C:\Projects\Logs\FF

Is there an expression/string that would say go back until you find "Logs" and open it? (assuming you were always below it)

The same executable is run out of "Debug", "MNH" or "FF" at different times, the executable always should save it's log files into "Logs".

What expression would get there WITHOUT referring to the entire path C:\Projects\Logs?

Thanks.

+1  A: 

It sounds like you're asking about a relative path.

If the working directory is C:\Projects\Logs\RTC\MNH\Debug\, the path ..\..\..\file represents a file in the Logs directory.

If you might be in either C:\Projects\Logs\RTC\MNH\ or C:\Projects\Logs\RTC\MNH\Debug\, then no single expression will get you back to Logs from either place. You could try checking for the existence of ..\..\..\..\Logs and if that doesn't exist, try ..\..\..\Logs, ..\..\Logs and ..\Logs, which one exists would tell you how "deep" you are and how many ..s are required to get you back to Logs.

Tim Sylvester
+2  A: 

You might have luck using the boost::filesystem library.

Without a compiler (and ninja-copies from boost documentation), something like:

#include <boost/filesystem.hpp>

namespace boost::filesystem = fs;

bool contains_folder(const fs::path& path, const std::string& folder)
{
    // replace with recursive iterator to check within
    // sub-folders. in your case you just want to continue
    // down parents paths, though
    typedef fs::directory_iterator dir_iter;

    dir_iter end_iter; // default construction yields past-the-end
    for (dir_iter iter(path); iter != end_iter; ++iter)
    {
        if (fs::is_directory(iter->status()))
        {
            if (iter->path().filename() == folder)
            {
                return true;
            }
        }
    }

    return false;
}

fs::path find_folder(const fs::path& path, const std::string& folder)
{
    if (contains_folder(path, folder))
    {
        return path.string() + folder;
    }

    fs::path searchPath = path.parent_path();
    while (!searchPath.empty())
    {
        if (contains_folder(searchPath, folder))
        {
            return searchPath.string() + folder;
        }

        searchPath = searchPath.parent_path();
    }

    return "":
}

int main(void)
{
    fs::path logPath = find_folder(fs::initial_path(), "Log");

    if (logPath.empty())
    {
        // not found
    }
}

For now this is completely untested :)

GMan