在Linux中使用C ++更改当前目录 [英] Changing the current directory in Linux using C++

查看:915
本文介绍了在Linux中使用C ++更改当前目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

  #include< iostream> 
#include< string>
#include< unistd.h>

using namespace std;

int main()
{
//变量
string sDirectory

//要求用户移动到
目录$ cout<< 请输入目录...<< endl
cin>> sDirectory;
cin.get();

//导航到用户指定的目录
int chdir(sDirectory);

return 0;
}

这段代码的目的是非常明确的:设置一个用户指定的目录作为当前目录。我的计划是对其中包含的文件进行操作。但是,当我尝试编译此代码时,我收到以下错误

 错误:无法将'std :: string' 'int'in initialization 

引用 int chdir (sDirectory)。我刚刚开始编程,现在只是开始找到平台的具体功能,这是一个是所以任何帮助这个问题将非常感激。

c> c> c> c> cdc c $ c>函数。它是一个使用无效的字符串初始化器(`sDirectory)的 int 声明为 chdir



要调用你只需要做的功能:

  chdir(sDirectory.c_str )); 

注意chdir需要一个 const char * ,而不是 std :: string ,因此您必须使用 .c_str()



如果你想保留返回值,你可以声明一个整数并使用 chdir 调用来初始化它,但是你必须给出 int a name:

  int chdir_return_value = chdir(sDirectory.c_str ; 

最后,请注意,在大多数操作系统中,当前目录或工作目录只能为进程本身设置和他创造的任何孩子。



如果你希望找到你的shell的工作目录,一旦你的程序终止,就改变它。你很可能会失望。


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, when 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.

这篇关于在Linux中使用C ++更改当前目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆