在Windows上编辑HOSTS文件

时间:2011-11-05 03:13:04

标签: c++ windows hosts

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

所以,是的,我已经尝试以管理员身份运行该程序,但它仍然无效。我的程序如何读取/编辑以管理员身份运行的HOSTS?

2 个答案:

答案 0 :(得分:5)

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

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

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

答案 1 :(得分:1)

问题可能是你在文件路径中使用了不作为\\进行转义的反斜杠?

相关问题