I’m noob in C++ but wanting to learn. I have a little program that writes some info to my \etc\hosts in Windows; I get the %WINDIR% variable via GetEnvironmentVariable(), if I put the full path manually everything is ok, but when I substitute with WINDIR variable my code isn’t compiling. I know I don’t do something right.
#include <windows.h>
#include <ios>
#include <fstream>
char buffer[1000];
int main() {
GetEnvironmentVariable("WINDIR",(char*)&buffer,sizeof(buffer));
std::ofstream log;
log.open("%s\\system32\\drivers\\etc\\hosts", buffer);
log << "127.0.0.1 domain.com\n" << std::endl;
return 0;
}
I get really ugly errors like:
C:\Documents and Settings\xtmtrx\Desktop\coding\windir.cpp no matching function for call to `
std::basic_ofstream<char, std::char_traits<char> >::open(const char[30], char[1000])‘
ofstreamcannot format the path for you. You need to do that separately, eg:FYI, you should use
GetWindowsDirectory(),GetSystemDirectory(),SHGetSpecialFolderPath()orSHGetKnownFolderPath()instead ofGetEnvironmentVariable(). And you should usePathCombine()when concantenating paths together so it can ensure the slashes are correct.