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 clear: set the directory specified by the user as the current directory. My plan is to perform operations on the files contained in it. However, when I try to compile this code, I get the following error:

error: cannot convert β€˜std::string’ to β€˜int’ in initialization

with reference to reading the line int chdir(sDirectory). I just started programming, and now I'm just starting to learn about the platform-specific functions that are in this, so any help on this would be most appreciated.

+5
source share
3 answers

int chdir(sDirectory); chdir. int, chdir (`sDirectory).

, :

chdir(sDirectory.c_str());

, chdir const char*, std::string, .c_str().

, chdir , int :

int chdir_return_value = chdir(sDirectory.c_str());

, , . () , , .

, , , , .

+8
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.
}
+5

The problem is that you are a string to pass an STL string to chdir (). chdir () requires a C-style string, which is just an array of characters ending in a NUL byte.

What you need to do is chdir(sDirectory.c_str())that which converts it to a C-style string. And also an int on is int chdir(sDirectory);not required.

+2
source

All Articles