【问题标题】:Editing HOSTS file on Windows在 Windows 上编辑 HOSTS 文件
【发布时间】:2011-11-05 03:13:04
【问题描述】:

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

所以,是的,我尝试以管理员身份运行该程序,但它仍然无法正常工作。我的程序如何读取/编辑以管理员身份运行的主机?

【问题讨论】:

  • f.is_open()返回false,表示fstream f ("C:\\Windows\\System32\\drivers\\etc\\hosts");无法打开hosts文件。

标签: c++ windows hosts


【解决方案1】:

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

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

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

【讨论】:

  • 确实必须纠正。但是程序仍然无法访问主机! ://
  • 好的,接下来要检查的是权限。通常非管理员用户不能写入 hosts 文件,fstream 会打开以读取 写入。如果您使用ifstream 而不是fstream,因为您只是在阅读,该怎么办?
【解决方案2】:

也许问题是您在文件路径中使用了未转义为 \\ 的反斜杠?

【讨论】:

    猜你喜欢
    • 2014-08-07
    • 2014-08-04
    • 2011-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多