头文件

#include <unistd.h>

使用

    char path[200];
if(!getcwd(path,200)){
cout<<"Get path fail!"<<endl;
return 0;
}
cout<<"path:"<<path<<endl;

open配合

file.open("/mnt/c/Users/zhifeiyu/Documents/0学习课件/大三上学习课件/程序设计/script_interpreter/dev/a.txt",ios::in);

### 完整代码测试

//当前目录下有a.txt
#include<iostream>
using namespace std;
#include <unistd.h>
#include<fstream>

int main(){
   //获取当前路径
   char path[200];
if(!getcwd(path,200)){
cout<<"Get path fail!"<<endl;
return 0;
}
// cout<<"path:"<<path<<endl;
   string spath(path);
   // cout << "spath:" << spath <<endl;
   //构造绝对路径
   spath += "/a.txt";
   //使用构造的绝对路径打开文件
   fstream file;
   file.open(spath,ios::in);
   if(!file.is_open()){
       cout << "open error" << endl;
       exit(-1);
  }else{
       cout << "open success" << endl;
  }
   file.close();
   return 0;
}

 

posted on 2021-12-18 23:17  彼岸花不开彼岸  阅读(667)  评论(0)    收藏  举报