lucasn
lucasn

Reputation: 137

Editing HOSTS file on Windows

I'm writing an application that manages the hosts files entries. So I wrote a little code in C++ trying to access and read the HOSTS file:

#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;
}

Before making this question, i've read this one: edit the etc\hosts file

So, yes, I've tried running the program as admin, but it still doesn't work. How can my program read/edit the HOSTS running as admin?

Upvotes: 2

Views: 5320

Answers (2)

Greg Hewgill
Greg Hewgill

Reputation: 992697

In C++, you must quote backslashes in string literals. So try:

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

This is because using a single backslash like \n means something special to the compiler.

Upvotes: 5

enticedwanderer
enticedwanderer

Reputation: 4346

Perhaps the problem is you are using back slashes in the file path that are not escaped as \\?

Upvotes: 1

Related Questions