0

I want to change to the directory specified by the path. The filename is a string and is included in the path.

I have stored the filename in a string and I am adding this filename to the path. Next using chdir() I am changing to the directory specified by the path.

I know that the filename can be specified in the path itself, but I want it to do it this way because the filename will be keep on changing.

int main()
{
    system("echo -n '1. Current Directory is '; pwd");

    std::string filename ("1184581000.pcd");

    cout<<filename;

    chdir("/home/usrn/pcd/"+ filename"");

    system("echo -n '1. Current Directory is '; pwd");

    return 0;  
}

The result is:

error: expected ‘)’ before string constant
 chdir("/home/usrn/pcd/"+ ls"");

error: cannot convert ‘std::__cxx11::basic_string<char>’ to ‘const char*’ for argument ‘1’ to ‘int chdir(const char*)’
chdir("/home/usrn/pcd/"+ ls"");
jww
  • 97,681
  • 90
  • 411
  • 885
Goalscorer
  • 21
  • 5
  • 2
    In C++17, you might use [std::filesystem::current_path](https://en.cppreference.com/w/cpp/filesystem/current_path). – Jarod42 Jun 11 '19 at 12:59

1 Answers1

-1

Syntax should be:

chdir(("/home/usrn/pcd/"+ filename).c_str());
Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • Thanks,The errors are gone,but it is not changing the directory. I am getting the output as 1. Current Directory is /home/usrn 1. Current Directory is /home/usrn – Goalscorer Jun 11 '19 at 13:03
  • 3
    @Goalscorer - You can't `chdir` to a filename. The `chdir` is failing. Check return values. – jww Jun 11 '19 at 13:06
  • Ok,sorry I didn't know that – Goalscorer Jun 11 '19 at 13:07
  • 2
    @Goalscorer - Leave the filename off of the `chdir`. Also see [Is there any way to change directory using C language?](https://stackoverflow.com/q/1293660/608639), [How to chdir using C in Linux environment](https://stackoverflow.com/q/13204650/608639), etc. – jww Jun 11 '19 at 13:10