2009-09-17 158 views
0
C:\Projects\Logs\RTC\MNH\Debug 
C:\Projects\Logs\FF 

有没有一个表达式/字符串,会说回去,直到你找到“日志”并打开它? (假设你总是在它下面)目录结构C++

相同可执行文件在不同时间用完“Debug”,“MNH”或“FF”,可执行文件总是应该将它的日志文件保存到“日志”中。

什么表达式将不会引用整个路径C:\ Projects \ Logs?

谢谢。

回答

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,哪一个存在会告诉您您有多“深”,需要多少个..才能让您回到Logs

3

您可能使用boost::filesystem库运气。

没有一个编译器(以及从升压文档忍者副本),是这样的:

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

现在这是完全未经测试:)