【问题标题】:relative path for searching directory with FindFirstFile使用 FindFirstFile 搜索目录的相对路径
【发布时间】:2013-02-20 01:14:28
【问题描述】:

在包含我的 exe 的目录中,我有一个名为“saves”的文件夹。 我想显示这个目录包含的文件。

我使用了这里找到的代码: Listing directory contents using C and Windows

现在是棘手的部分。 如果我使用.\\saves\\ 作为我的目录,它会告诉我找不到路径。 但是,如果我使用 ..\\release\\saves\\ 它工作正常。但那很愚蠢。我不想转到父文件夹然后返回。特别是关于我不知道用户给包含 exe 的目录起什么名字(在我的情况下它是“发布”但谁知道用户做了什么:-D)。

我阅读了这个:http://msdn.microsoft.com/en-us/library/aa365247(v=vs.85).aspx#fully_qualified_vs._relative_paths,但它并没有太大帮助。

我也尝试过saves\\.\saves\\,但也没有用。

我希望有人能告诉我如何解决这个问题。

【问题讨论】:

    标签: c++ path relative-path


    【解决方案1】:

    您实际上在代码中没有做错任何事情 - 您一直在从 Visual Studio 启动项目,它将工作目录设置为 Release/Debug 文件夹的父级。

    进入项目->设置(属性)->配置属性->调试->工作目录

    您也可以在 VS 之外运行 exe,相对路径的行为将与您预期的一样。

    【讨论】:

      【解决方案2】:

      我认为您的错误是使用 \\saves\\ 并忘记指定搜索参数/字符串
      你应该使用:

      saves\\*
      

      这将搜索任何文件或文件夹

      【讨论】:

      • 嘿,我通过sprintf(sPath, "%s\\*.*", sDir);添加了一个搜索掩码
      【解决方案3】:

      如果它是相对于可执行文件的路径,而不是相对于当前工作目录的路径,您可以使用GetModuleFileName() 获取可执行文件的完整路径。然后,从路径末尾删除可执行文件的名称并使用该名称构建路径:

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

      【讨论】:

        【解决方案4】:

        我会使用boost::filesystem http://www.boost.org/doc/libs/1_53_0/libs/filesystem/doc/index.htm

        作为奖励,您将获得独立于操作系统的代码。

        【讨论】:

          猜你喜欢
          • 2020-07-28
          • 2021-08-31
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-12-11
          • 1970-01-01
          相关资源
          最近更新 更多