【问题标题】:directory structures C++目录结构 C++
【发布时间】:2009-09-17 21:52:12
【问题描述】:
C:\Projects\Logs\RTC\MNH\Debug  
C:\Projects\Logs\FF

是否有一个表达式/字符串会说返回直到找到“日志”并打开它? (假设你总是在它下面)

同一个可执行文件在不同时间用完“Debug”、“MNH”或“FF”,可执行文件总是应该将其日志文件保存到“Logs”中。

如果不引用整个路径 C:\Projects\Logs,会出现什么表达式?

谢谢。

【问题讨论】:

    标签: c++ c file active-directory


    【解决方案1】:

    使用boost::filesystem 库你可能会很幸运。

    没有编译器(以及来自 boost 文档的忍者副本),类似于:

    #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
        }
    }
    

    目前这是完全未经测试的:)

    【讨论】:

      【解决方案2】:

      听起来你在问相对路径。

      如果工作目录为C:\Projects\Logs\RTC\MNH\Debug\,则路径..\..\..\file代表Logs目录中的一个文件。

      如果您可能在 C:\Projects\Logs\RTC\MNH\C:\Projects\Logs\RTC\MNH\Debug\ 中,那么任何一个表达式都不会让您从任一位置回到 Logs。您可以尝试检查..\..\..\..\Logs 是否存在,如果不存在,请尝试..\..\..\Logs..\..\Logs..\Logs,哪个存在会告诉您您有多“深”以及有多少..需要 s 才能让您回到 Logs

      【讨论】:

        猜你喜欢
        • 2010-11-26
        • 1970-01-01
        • 1970-01-01
        • 2013-07-11
        • 2012-08-24
        • 2013-06-20
        • 2017-11-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多