纯C/C++程序中如何获取当前目录和程序目录
不用Windows库(主要是控制台编程),可以用STL库。
标准C/C++函数最好,如果标准C/C++里没有,请分别给出在Windows和Linux下的方案。
据说chdir可以修改当前目录,但当前目录是在哪里用什么获取呢?
main的第0个参数是命令本身,但是可执行文件的路径是什么呢?
[解决办法]
long getcwd(char *buf, unsigned long size);
[解决办法]
用Qt吧,Windows/Linux/Mac都是一样的函数
[解决办法]
函数名称: getcwd
函数原型: char *getcwd(char *dir,int len)
函数功能: 得到当前路径名称
函数返回: 指向dir的指针
参数说明: len-路径最大长度.dir-路径字符串.
所属文件: <dir.h>
#include <stdio.h>
#include <dir.h>
int main()
{
char buffer[MAXPATH];
getcwd(buffer, MAXPATH);
printf( "The current directory is: %s ", buffer);
return 0;
}
[解决办法]
当前工作目录 getcwd
程序目录 GetModuleFileName(NULL, str, sizeof(str))
[解决办法]
当前目录:
getcwd
程序目录:
win32:GetModuleFileName
linux:readlink
[解决办法]
Linux 下可以用 readlink /proc/self/exe 的方法得到。