[英]How to search in the system path for a file?
我在系统路径的某个文件夹中有x.dll
。 而且我在同一文件夹中还有另一个文件x.zzz
,这不是可执行文件。
从C ++程序,我想搜索x.zzz
而不加载x.dll
。 但是我希望LoadLibrary
像LoadLibrary
函数一样工作。 即,它的搜索顺序应与LoadLibrary
。
这可能吗?
PS:我检查了SearchPath()
函数,但文档中有一条说明说不应将此用于此目的。
如果对输出的预期用途是在对LoadLibrary函数的调用中,则不建议将SearchPath函数作为查找.dll文件的方法。 因为SearchPath函数的搜索顺序与LoadLibrary函数使用的搜索顺序不同,这可能导致找到错误的.dll文件。 如果您需要查找并加载.dll文件,请使用LoadLibrary函数。
使用任何内置函数的问题是,他们将专门寻找可执行文件或dll。 我想说的最好的选择是实际解析路径变量并手动遍历目录。 可以使用C函数进行目录迭代。 以下内容适用于大多数平台。
#include <dirent.h>
#include <cstdlib>
#include <iostream>
#include <string>
...
std::string findInPath(const std::string &key, char delim = ';');
std::string findInDir(const std::string &key, const std::string &dir);
...
std::string findInDir(const std::string &key, const std::string &directory)
{
DIR *dir = opendir(directory.c_str());
if(!dir)
return "";
dirent *dirEntry;
while(dirEntry = readdir(dir))
{
if(key == dirEntry->d_name) // Found!
return directory+'/'+key;
}
return "";
}
std::string findInPath(const std::string &key, char delim)
{
std::string path(std::getenv("PATH"));
size_t posPrev = -1;
size_t posCur;
while((posCur = path.find(delim, posPrev+1)) != std::string::npos)
{
// Locate the next directory in the path
std::string pathCurrent = path.substr(posPrev+1, posCur-posPrev-1);
// Search the current directory
std::string found = findInDir(key, pathCurrent);
if(!found.empty())
return found;
posPrev = posCur;
}
// Locate the last directory in the path
std::string pathCurrent = path.substr(posPrev+1, path.size()-posPrev-1);
// Search the current directory
std::string found = findInDir(key, pathCurrent);
if(!found.empty())
return found;
return "";
}
如何将LoadLibraryEx()与标志LOAD_LIBRARY_AS_IMAGE_RESOURCE一起使用?
如果使用此值,则系统会将文件作为映像文件映射到进程的虚拟地址空间。 但是,加载程序不会加载静态导入或执行其他常规初始化步骤。 当您只想加载DLL以便从中提取消息或资源时,请使用此标志。
我意识到您说的是“未加载” ...但是使用这种技术可以防止.dll的函数和变量污染您的命名空间,等等。如果您有性能要求,或某些其他特定原因指定“未加载”,请执行扩大。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.