Changing the current directory in Linux using C++
I have the following code:
#include <iostream>
#include <string>
#include <unistd.h>
using namespace std;
int main()
{
// Variables
string sDirectory;
// Ask the user for a directory to move into
cout << "Please enter a directory..." << endl;
cin >> sDirectory;
cin.get();
// Navigate to the directory specified by the user
int chdir(sDirectory);
return 0;
}
The purpose of this code is pretty self explanatory: to set a user specified directory as the current directory. My plan is to carry out operations on the files contained therein. However, whe开发者_开发问答n I attempt to compile this code, I receive the following error
error: cannot convert ‘std::string’ to ‘int’ in initialization
with reference being made to the line reading int chdir(sDirectory)
. I've just started programming and am only now starting to have to find out about platform specific functions, which this one is, so any help on this matter would be most appreciated.
int chdir(sDirectory);
isn't the correct syntax to call the chdir
function. It is a declaration of an int
called chdir
with an invalid string initializer (`sDirectory).
To call the function you just have to do:
chdir(sDirectory.c_str());
Note that chdir takes a const char*
, not a std::string
so you have to use .c_str()
.
If you want to preserve the return value you can declare an integer and use a chdir
call to initialize it but you have to give the int
a name:
int chdir_return_value = chdir(sDirectory.c_str());
Finally, note that in most operating system the current or working directory can only be set for the process itself and any children it creates. It (almost) never affects the process that spawned the process changing its current directory.
If you expect to find the working directory of your shell to be changed once your program terminates you are likely to be disappointed.
if (chdir(sDirectory.c_str()) == -1) {
// handle the wonderful error by checking errno.
// you might want to #include <cerrno> to access the errno global variable.
}
The issue is that you are string to pass an STL string to chdir(). chdir() requires a C Style string, which is just an array of characters terminated with a NUL byte.
What you need to be doing is chdir(sDirectory.c_str())
which will convert it to a C Style string. And also the int on int chdir(sDirectory);
isn't necessary.
精彩评论