linux下cd到可执行文件所在的目录(c++)

rt,可执行文件不应该受限于调用它时所在的路径。


在shell中,可以这样搞:

cd `dirname $0`


在c++中如何做呢?

在我们的main函数开始的时候,调用一下这个方法,是个好主意。


代码如下:

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

using namespace std;



int chdirName0(){
  int ret = -1;
  string _curPath_s_;
  char _exec_name_ [BUFSIZ];
  ret = readlink ("/proc/self/exe", _exec_name_, BUFSIZ);
  if(ret==-1){
    printf("get exec file's path failed.\n");
    return -1;
  }
  string _temp_s_ = _exec_name_;
  int _index_s_ = _temp_s_.find_last_of("/");
  if(_index_s_==string::npos){
    printf("get exec file's dir path failed.\n");
    return -2;
  }
  _curPath_s_ = _temp_s_.substr(0, _index_s_);
  ret = chdir(_curPath_s_.c_str());
  if(ret!=0){
    printf("chdir error.\n");
    return -3;
  }

  

  return 0;
} 

int main(){
  chdirName0();

  char pwd[100];
  printf("%s\n", getcwd(pwd, 100));

}



具体效果如下:


[work@xxx sb7]$ g++ -o b ch.cpp
[work@xxx sb7]$ ./b
/home/work/gaofeng/sb7
[work@xxx sb7]$ cd ../..
[work@xxx ~]$ ./gaofeng/sb7/b
/home/work/gaofeng/sb7




在 /usr/include/unistd.h中有这样的函数可以使用:

chdir 类似于cd那个操作
getcwd 获得当前工作目录

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值