是否有 API 调用可以显示主机文件在给定系统上的位置?
Is there an API call that will show me the location of a hosts file on given system?
我的意思是用户运行程序实际使用的文件。
或者我必须手动检查可能的路径,如此table:https://en.wikipedia.org/wiki/Hosts_%28file%29#Location_in_the_file_system
Is there an API call that will show me the location of a hosts file on given system?
不,没有这样的 API 调用。如果你想访问它,你需要知道文件在哪里。
没有可用于查找 hosts 文件所在目录的 Windows API 调用。但是,正如您问题中的 Wikipedia article 中所述,该文件位于 %SystemRoot% 目录的固定子目录中。
您可以检索 %SystemRoot% 的完全限定路径名(与 %WinDir% for NT-based systems) calling SHGetKnownFolderPath passing a FOLDERID_Windows KNOWNFOLDERID 相同。
以下代码 returns 所有受支持版本 Windows 上主机文件的完全限定路径名:
#include <comdef.h>
#include <ShlObj.h>
#include <string>
std::wstring GetHostsPathName() {
wchar_t* systemRoot;
_com_util::CheckError( ::SHGetKnownFolderPath( FOLDERID_Windows,
0x0,
nullptr,
&systemRoot ) );
std::wstring hostsPathName( systemRoot );
::CoTaskMemFree( systemRoot );
systemRoot = nullptr;
hostsPathName.append( L"\System32\drivers\etc\hosts" );
return hostsPathName;
}
我的意思是用户运行程序实际使用的文件。
或者我必须手动检查可能的路径,如此table:https://en.wikipedia.org/wiki/Hosts_%28file%29#Location_in_the_file_system
Is there an API call that will show me the location of a hosts file on given system?
不,没有这样的 API 调用。如果你想访问它,你需要知道文件在哪里。
没有可用于查找 hosts 文件所在目录的 Windows API 调用。但是,正如您问题中的 Wikipedia article 中所述,该文件位于 %SystemRoot% 目录的固定子目录中。
您可以检索 %SystemRoot% 的完全限定路径名(与 %WinDir% for NT-based systems) calling SHGetKnownFolderPath passing a FOLDERID_Windows KNOWNFOLDERID 相同。
以下代码 returns 所有受支持版本 Windows 上主机文件的完全限定路径名:
#include <comdef.h>
#include <ShlObj.h>
#include <string>
std::wstring GetHostsPathName() {
wchar_t* systemRoot;
_com_util::CheckError( ::SHGetKnownFolderPath( FOLDERID_Windows,
0x0,
nullptr,
&systemRoot ) );
std::wstring hostsPathName( systemRoot );
::CoTaskMemFree( systemRoot );
systemRoot = nullptr;
hostsPathName.append( L"\System32\drivers\etc\hosts" );
return hostsPathName;
}