【问题标题】:How can I write a piece of code in C++ to find the full path of a file that is on the system path? [closed]如何在 C++ 中编写一段代码来查找系统路径上文件的完整路径? [关闭]
【发布时间】:2016-05-10 20:45:59
【问题描述】:

使用 C++(在 Visual Studio 2013 中),我如何编写一段代码来搜索特定文件的系统路径并返回文件的完整路径?我只有文件的基本名称。这里所说的系统路径,是指windows中的路径环境变量(你可以通过在命令窗口中输入“set path”来查看路径)。

例如。我喜欢有类似的东西,

file_name = "my_test.xml"
path = find_file(fine_name);

提前致谢


我想出了答案。下面是一段完全符合我要求的代码:

#include <iostream>
#include <Shlwapi.h>

wchar_t* get_file_full_path(const wchar_t file_name[]){
    wchar_t buf[MAX_PATH];
    wcscpy_s(buf, wcslen(file_name) + 1, file_name);
    if (PathFindOnPath(buf, NULL)) {
        std::wcout << file_name << " found." << std::endl;
        std::wcout << buf << std::endl;
    }
    else {
        std::wcout << "Could not find the file " << file_name << " on the system path.";
    }
    return buf;
}

【问题讨论】:

标签: c++ windows path


【解决方案1】:

你可以先检查系统路径,如果没有找到,你需要在机器里搜索文件。 根据您的开发环境,有不同的方法。假设您使用的是 Windows 系统,这是一个示例:

#include <Windows.h>
#include <iostream>
int main()
{
    WIN32_FIND_DATA file;
    HANDLE search_handle=FindFirstFile(L"C:\\*",&file);
    if (search_handle)
    {
        do
        {
            std::wcout << file.cFileName << std::endl;
        }while(FindNextFile(search_handle,&file));
        CloseHandle(search_handle);
    }
}

【讨论】:

  • 这是一个非常相关的答案。它打印出 C:\ 目录中的所有文件和文件夹。如果我需要找到一个我不知道它在哪里的文件,而我只知道它位于路径上的某个目录中,该怎么办?
  • 然后您应该检查 PATH 上的每个位置。您需要从环境变量中读取 PATH,通常是“;”划定的。然后将每个位置替换为程序当前查看 C:\* 目录的位置。
  • 请查看我在顶部发布的解决方案。我觉得它更直接。感谢您对此问题的意见。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-29
  • 1970-01-01
  • 2013-03-30
  • 2014-07-14
  • 1970-01-01
  • 2011-02-02
相关资源
最近更新 更多