在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;
}
}
结果:
附件:
//路径转化
#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;
}