C ++使用GetEnvironmentVariable()中的完整PATH写入文件错误

时间:2012-12-29 18:13:40

标签: c++ compiler-errors environment-variables

我是C ++中的菜鸟但想要学习。我有一个小程序,可以将一些信息写入Windows中的\etc\hosts;我通过%WINDIR%得到GetEnvironmentVariable()变量,如果我手动输入完整路径一切正常,但当我用WINDIR变量替换时,我的代码没有编译。我知道我做的不对。

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

我得到了非常难看的错误,如:

  

C:\ Documents and Settings \ xtmtrx \ Desktop \ coding \ windir.cpp没有匹配函数来调用“std::basic_ofstream<char, std::char_traits<char> >::open(const char[30], char[1000])

3 个答案:

答案 0 :(得分:2)

ofstream无法为您格式化路径。您需要单独执行此操作,例如:

#include <windows.h>
#include <ios>
#include <fstream>

char buffer[1000] = {0};
int main() {
    GetEnvironmentVariable("WINDIR",buffer,sizeof(buffer));
    strcat(buffer, "\\system32\\drivers\\etc\\hosts");
    std::ofstream log;
    log.open(buffer, ios_base::ate);
    log << "127.0.0.1   domain.com\n" << std::endl;
    return 0;
}

仅供参考,您应该使用GetWindowsDirectory()GetSystemDirectory()SHGetSpecialFolderPath()SHGetKnownFolderPath()代替GetEnvironmentVariable()。并且在将路径连接在一起时应该使用PathCombine(),这样可以确保斜杠是正确的。

答案 1 :(得分:1)

您需要将字符串连接在一起,如下所示:

LPTSTR windir[MAX_PATH];
LPTSTR fullpath[MAX_PATH];
GetWindowsDirectory(windir, MAX_PATH);
if(PathCombine(fullpath, windir, _T("system32\\drivers\\etc\\hosts")) != NULL) {
    std::ofstream log;
    log.open(buffer, ios_base::ate);
    log << "127.0.0.1   domain.com\n" << std::endl;
}

首先,您需要使用PathCombine连接目录和文件部分。然后,您可以打开文件并编写内容。您还应注意,您需要管理员权限才能更改此文件,某些防病毒程序可能会拒绝访问hosts文件。

答案 2 :(得分:1)

open("%s\\system32\\drivers\\etc\\hosts", buffer); open不理解格式字符串..您正在使用%s没有意义。学习here

试试这样:

GetEnvironmentVariable("WINDIR",buffer,sizeof(buffer));
strcat(buffer, "\\system32\\drivers\\etc\\hosts");
std::ofstream log;
log.open(buffer.str().c_str(), ios_base::ate);   
相关问题