简体   繁体   中英

Converted string to char, when i cout the char it is correct but when I use chdir with the char it does not work?

I am working on a program that includes the ability to print the working directory and change directories. Originally I had the user typing 'cd' which would call the cd function and ask them which directory to change to. This worked fine however I wanted to be able to do something like "cd /Users" all in one line. I've managed to split the string and pass the split part to the character variable I'm using for chdir fine, but for some reason chdir is not actually changing the directory with this method.

`void exec_cd(std::string destination)
{
    int BUFFER_SIZE = 1024;
    char *directory;
    directory = new char [BUFFER_SIZE]; //Allocated memory in order to cin to the pointer char
    strcpy(directory, destination.c_str()); //Copy destination string into char directory
    //std::cout << "Enter target directory: " << std::endl << ">";
    //std::cin >> directory;
    std::cout << "TEST: " << directory;
    chdir(directory);
    delete [] directory;
}`

I commented out the old lines I had in there, when those were there instead of strcpy it worked fine. This function is passed everything entered after cd, I know the strcpy is doing its job because the line with "TEST :" outputs whatever it is supposed to (eg I type cd /Users) and it will show that directory indeed holds '/Users' it just is not working with chdir for some reason. I have a pwd function that works fine as far as I know but I will post that here too.

    void exec_pwd()
{
    long size;
    char *buf; //buffer holder
    char *ptr; //where the current directory will be saved to


    size = pathconf(".", _PC_PATH_MAX); //Gets size of path and saves it to size var.


    if ((buf = (char *)malloc((size_t)size)) != NULL) //Set buff = size of char * allocated size, if not null then get wd
        ptr = getcwd(buf, (size_t)size);

    std::cout << ptr << std::endl;
}

确认目标目录中有空白,并添加了修剪功能以消除问题前后的空间。

You may find that converting OS errors to error_code s as soon as possible is helpful.

#include <unistd.h>
#include <cerrno>
#include <system_error>
#include <iostream>


std::error_code change_directory(std::string const& str)
{
    std::error_code result;
    if(chdir(str.c_str()))
    {
        result = std::error_code(errno, std::system_category());
    }
    return result;
}

void throw_on_failure(std::error_code ec)
{
    if (ec) throw std::system_error(ec);
}


int main(int argc, char** argv)
{
    try
    {
        throw_on_failure(change_directory(argv[1]));
    }
    catch(std::exception const& e)
    {
        std::cout << e.what() << '\n';
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM