真不敢相信还没有人声称对这件事有悬念!!!
这是一个跨平台的实现,它使用C ++获取和更改当前的工作目录。 它所需要的只是一点宏观魔术,可以读取argv [0]的值,并定义一些小功能。
这是将目录更改为当前正在运行的可执行文件的位置的代码。 可以轻松地将其更改为将当前工作目录更改为所需的任何目录。
代码:
#ifdef _WIN32
#include "direct.h"
#define PATH_SEP '\\'
#define GETCWD _getcwd
#define CHDIR _chdir
#else
#include "unistd.h"
#define PATH_SEP '/'
#define GETCWD getcwd
#define CHDIR chdir
#endif
#include
#include
#include
using std::cout;
using std::endl;
using std::string;
string GetExecutableDirectory(const char* argv0) {
string path = argv0;
int path_directory_index = path.find_last_of(PATH_SEP);
return path.substr(0 , path_directory_index + 1);
}
bool ChangeDirectory(const char* dir) {return CHDIR(dir) == 0;}
string GetCurrentWorkingDirectory() {
const int BUFSIZE = 4096;
char buf[BUFSIZE];
memset(buf , 0 , BUFSIZE);
GETCWD(buf , BUFSIZE - 1);
return buf;
}
int main(int argc , char** argv) {
cout << endl << "Current working directory was : " << GetCurrentWorkingDirectory() << endl;
cout << "Changing directory..." << endl;
string exedir = GetExecutableDirectory(argv[0]);
ChangeDirectory(exedir.c_str());
cout << "Current working directory is now : " << GetCurrentWorkingDirectory() << endl;
return 0;
}
输出:
c:\ Windows> c:\ ctwoplus \ progcode \ test \ CWD \ cwd.exe
当前工作目录为:c:\ Windows正在更改目录...当前工作目录为:c:\ ctwoplus \ progcode \ test \ CWD
c:\ Windows>