C++ 获取当前路径

在C++ 中可以通过 _getcwd函数来获取当前文件所在文件夹的路径,
其函数原型为:

char * _cdecl _getcwd(char *_DstBuf,int _SizeInBytes)
/*
	头文件: <direct.h>
	参数:_DstBuf:指向当前路径字符串的字符指针,getcwd函数会将当前路径复制到其指向的内存空间
	参数:_SizeInBytes:存储该路径字符串的内存空间的长度,_DstBuf指向的内存空间的长度
	返回值:指向路径字符串内存空间的指针
	说明:
		getcwd既可以将指定指针传入函数,将当前路径放到其内存空间中;
		也可以通过返回值直接获取指向当前路径字符串的指针
*/

使用范例

#include <iostream>
#include <fstream>
#include "stdlib.h"
#include <direct.h>
using namespace std;

int main()
{
    /*ifstream file1;
    ofstream file2;
    file1.open("C:\\Users\\cell1\\Desktop\\c++\\C++_study_prorammer\\filebuffer_test\\file1.txt",ios_base::in);
    file2.open("C:\\Users\\cell1\\Desktop\\c++\\C++_study_prorammer\\filebuffer_test\\file2.txt", ios_base::out);
    char temp[256];
    while (!file1.eof()) {
        file1.getline(temp, 128);
        cout << temp << endl;
        file2 << temp << endl;
    }
    file1.close();*
    file2.close();*/
    char cwd[256];
    _getcwd(cwd, 256);
    cout << cwd << endl;
    char* path;
    if ((path = _getcwd(NULL, 0)) == NULL) {
        cerr << "Error message : _getcwd error"<< endl;
    }
    else {
        cout << path << endl;
    }
}

结果:
_getcwd结果

附件:

//路径转化
#include <iostream>
#include <fstream>
#include "stdlib.h"
#include <direct.h>
#include <string>
using namespace std;

int main()
{
    char* cwd;
    cwd = _getcwd(NULL, 0);
    string* path = new string(cwd);
    string::size_type p=path->find("\\");
    while (p != string::npos) {
        p= p = path->find("\\");
        if (p!=string::npos)
        {
            path->replace(p, 1, "/");
        }
    }
    
    cout << *path<<endl;
}
  • 6
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值