2015-11-06 22 views

回答

1

没有可用于查找目录的Windows API调用,其中主机文件所在的目录。但正如您在问题中的Wikipedia article中所解释的那样,该文件位于%SystemRoot%目录的固定子目录中。

您可以检索完全合格的路径名的%SystemRoot%(这是一样的%WinDir% for NT-based systems)调用SHGetKnownFolderPath传递FOLDERID_WindowsKNOWNFOLDERID

下面的代码返回完全合格的路径名的主机上的所有支持的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; 
} 
1

是否有一个API调用会告诉我给出系统的hosts文件的位置?

不,没有这样的API调用。如果你想访问它,你需要知道文件的位置。

相关问题