Search code examples
cwindowsnetwork-programmingfopen

fopen is unable to open windows hosts file


I am having a FILE* target here which should open the windows hosts file and write to it:

FILE* target;
target = fopen("C:\\windows\\sysnative\\drivers\\etc\\hosts", "r+");
if (target != NULL) {
    printf("true\n");
} else {
    printf("false\n");
}

However, upon opening the windows hosts file, it fails to open it. Specifically, fopen() returns NULL and false is printed to the screen. I checked the directory. It is good. Removing the extra \s, I was able to open it with Notepad. However fopen() cannot open that file. It is able to open any file in the current working directory, or in a nested directory inside it, but it can't open the hosts file. Perhaps I have an issue with my path? Am I missing something?


Solution

  • you need admin priv to open hosts file on windows, try running your script as admin.