gpt4 book ai didi

c++ - 在 Windows 上编辑 HOSTS 文件

转载 作者:可可西里 更新时间:2023-11-01 09:48:57 24 4
gpt4 key购买 nike

我正在编写一个管理主机文件条目的应用程序。所以我用 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;
}

在提出这个问题之前,我读过这个:edit the etc\hosts file

所以,是的,我试过以管理员身份运行该程序,但它仍然不起作用。我的程序如何读取/编辑以管理员身份运行的主机?

最佳答案

在 C++ 中,您必须在字符串文字中引用 反斜杠。所以尝试:

fstream f ("C:\\Windows\\System32\\drivers\\etc\\hosts");

这是因为使用像 \n 这样的单个反斜杠对编译器来说意味着一些特殊的东西。

关于c++ - 在 Windows 上编辑 HOSTS 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8017922/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com