我正在编写一个管理主机文件条目的应用程序.所以我在C++中编写了一些代码来尝试访问和读取HOSTS文件:
#include <iostream>
#include <stdlib.h>
#include <fstream>
using namespace std;
int main(void)
{
string line;
fstream f ("C:\Windows\System32\drivers\etc\hosts");
if ( f.is_open() )
{
while ( f.good() )
{
getline(f,line);
cout << line << endl;
}
f.close();
} else
cout << "Error" << endl;
system("pause");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在提出这个问题之前,我已经读过这个:编辑etc\hosts文件
所以,是的,我已经尝试以管理员身份运行该程序,但它仍然无效.我的程序如何读取/编辑以管理员身份运行的HOSTS?
在C++中,您必须在字符串文字中引用反斜杠.所以尝试:
fstream f ("C:\\Windows\\System32\\drivers\\etc\\hosts");
Run Code Online (Sandbox Code Playgroud)
这是因为使用单个反斜杠就像\n是编译器特有的东西.