在Windows和Linux平台上使用c++获取文件当前路径
.h
#include <iostream>
#include <string>
#ifdef _WIN32
#include <windows.h> // 包含Windows API定义
#else
#include <limits.h> // 为了PATH_MAX
#include <unistd.h> // 为了getcwd
#endif // _WIN32
using namespace std;
#ifdef _WIN32
//获取当前路径
string getAbuselatePath() {
char buffer[MAX_PATH] = { 0 }; // MAX_PATH常量定义了路径的最大长度
// 获取当前目录
if (GetCurrentDirectoryA(MAX_PATH, buffer) != 0) {
return std::string(buffer); // 成功时返回当前目录
}
else {
// 如果失败,可以在这里处理错误
return std::string();
}
}
#else
//获取当前路径
string getAbuselatePath() {
char buffer[PATH_MAX];
if (getcwd(buffer, sizeof(buffer)) != NULL) {
return std::string(buffer); // 成功时返回当前目录
}
else {
// 如果失败,可以在这里处理错误
return std::string();
}
}
#endif // _WIN32
main.cpp
#include <iostream>
#include "abuselatePath.h"
int main()
{
string s = getAbuselatePath();
cout << s << endl;
}
Windows:
Linux: