【问题标题】:Const char concatenation and getenv()const char 连接和 getenv()
【发布时间】:2016-07-23 00:35:30
【问题描述】:

我正在经历学习c++的过程,所以我正在制作一些程序/工具来在计算机上进行一些简单的操作。在这个例子中,我正在创建一个程序来定位计算机上的浏览器(它将用于清除浏览器 cookie 等)。可能有更高级的方法可以更有效地执行此操作,但我目前正在尝试使其尽可能简单。

到目前为止,我正在尝试找出目录“C:\Program Files (x86)\Google\Chrome”是否存在。我使用getenv ("Program Files (x86)" 获取程序文件目录的地址,但之后如何添加其余地址? 我不能使用 + 运算符进行连接,因为变量是 const char *(bool PathIsDirectory() 需要 const char * 作为参数)。

std::cout << "Searching for browsers..." << std::endl;
const char *chromePath;
chromePath = getenv ("ProgramFiles(x86)");

bool result = PathIsDirectory(chromePath);

if(result == true)
{
    std::cout << "-- Google Chrome - FOUND" << std::endl;
}
else
{
    std::cout << "-- Google Chrome - NOT FOUND" << std::endl;
}

【问题讨论】:

  • 你真的能用getenv 得到ProgramFiles 的路径吗? getenv 用于检索环境变量。
  • 我怀疑ProgramFiles(x86) 表示一个有效的环境变量。
  • 使用std::string存储结果而不是const char*支持+
  • 您可以使用string.c_str() 获取const char * 用于C api。

标签: c++


【解决方案1】:

您可以将getenv() 的结果存储在std::string 对象中(如在 cmets)。然后你可以像这样使用 + 运算符添加路径的其余部分:

#include <string>
//...
std::string chromePath = getenv ("ProgramFiles(x86)");
chromePath += "\\remaining\\path";
bool result = PathIsDirectory(chromePath.c_str());

请注意,您必须如上所示转义反斜杠。

【讨论】:

  • 问题是PathIsDirectory()中不允许使用字符串变量,只能使用const char *作为参数。但是,我可以为 google chrome 目录的其余路径创建一个新的 const char * 变量,然后使用 strcat(const char * variable 1, const char * variable 2) 并将它们存储在最终的“完整路径” const char * 变量,在 PathIsDirectory() 中使用有效。见我上面的回答。
  • 正如@petesh 在问题cmets 中所说,您可以使用yourstring.c_str()std::string 获得const char*。您的自我回答不是一种安全的方法,因为它会调用未定义的行为。请考虑使用std::string
  • vu1p3n0x 是对的。我相应地更新了我的答案。看en.cppreference.com/w/cpp/string/byte/strcat。您会看到 strcat 实际上写入了 getenv() 的返回值所指向的内存。这是错误的,因为你不拥有那段记忆。
  • 谢谢你们,我会试试的。
猜你喜欢
  • 2010-12-31
  • 1970-01-01
  • 1970-01-01
  • 2018-11-03
  • 2011-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多