-2

I'm going through the process of learning c++, so I'm making a few programs/tools to do certain easy operations on the computer. In this example, I'm creating a program that will locate browsers on the computer (it will be used to clear browser cookies etc.). There is probably more advanced ways to do this more effieciently, but I'm trying to keep this as simple as possible at the moment.

So far, I'm trying to find out if the directory "C:\Program Files (x86)\Google\Chrome" exist. I get the address to the program files directory by using getenv ("Program Files (x86)", but how do I add the rest of the address after? I can't use the + operator for concatenation, since the variable is const char * (bool PathIsDirectory() requires const char * as parameter).

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;
}
saltcracker
  • 321
  • 3
  • 17

1 Answers1

3

You can store the result of getenv() in a std::string object (as mentioned in the comments). And then you can add the rest of the path using the + operator like this:

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

Note that you'll have to escape the backslashes as shown above.

tonisuter
  • 789
  • 5
  • 13
  • The problem is that string variables is not allowed in PathIsDirectory(), only const char * as parameter. I could however create a new const char * variable for the rest of the path to the google chrome directory, and then use strcat(const char * variable 1, const char * variable 2) and store them in a final "full path" const char * variable, valid to use in PathIsDirectory(). See my answer above. – saltcracker Apr 03 '16 at 14:18
  • 1
    As @petesh said in the question comments, you can get a `const char*` from `std::string` by using `yourstring.c_str()`. Your self answer is not a safe way to do it as it invokes undefined behaviour. Please consider using `std::string`. – kmdreko Apr 03 '16 at 14:20
  • vu1p3n0x is right. I updated my answer accordingly. Look at http://en.cppreference.com/w/cpp/string/byte/strcat. You'll see that strcat actually writes into the memory that is pointed to by the return value of getenv(). That is wrong, because you don't _own_ that memory. – tonisuter Apr 03 '16 at 14:22
  • Thank you guys, I will try that. – saltcracker Apr 03 '16 at 14:26