C程序中怎么得到本程序所在路径?

xzjxu 2005-10-19 05:53:27
如题
...全文
241 10 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
kaoyan2005 2005-10-19
  • 打赏
  • 举报
回复
wfh tc 什么意思
antijpn 2005-10-19
  • 打赏
  • 举报
回复
另外,直接求代码,转新手乐园
antijpn 2005-10-19
  • 打赏
  • 举报
回复
虫子不要说了,你都搞错了的说……getcwd完全不是你说的功能,current working directory是当前工作目录,而不是程序所在目录

shell工作的时候chdir就是改变工作路径的,你从shell里面用pwd得到的东西就是current working directory,这个随着你对chdir的调用会变化的……
antijpn 2005-10-19
  • 打赏
  • 举报
回复
以上方法均错误(就算能用,也不是可移植的)

可以用以下方法验证
#include <unistd.h>
#include <stdio.h>

int main(int argc, char *argv[])
{
printf("%s\n", argv[0]);
chdir("/usr/local");
printf("%s\n", getcwd(0,0));

return 0;
}

编译以后不要用绝对路径运行,这个是完全无法得到程序绝对路径的。

这样的功能必然是需要在进程信息中查寻的,看哪个系统的哪个结构里面有吧……
jixingzhong 2005-10-19
  • 打赏
  • 举报
回复
#include <dir.h>

函数原形:
char *getcwd(char *buf,int n)
jixingzhong 2005-10-19
  • 打赏
  • 举报
回复
int getcurdir(int drive,char *direc) 此函数返回指定驱动器的当前工作目录名称
drive 指定的驱动器(0=当前,1=A,2=B,3=C等)
direc 保存指定驱动器当前工作路径的变量 成功返回0

和楼主要求的相差有点大啊 ~
jixingzhong 2005-10-19
  • 打赏
  • 举报
回复
char *getcwd(char *buf,iint n) 此函数取当前工作目录并存入buf中,直到n个字节长为为止.错误返回NULL
ma100 2005-10-19
  • 打赏
  • 举报
回复
Declaration: int getcurdir(int drive, char *directory);

Remarks:
getcurdir gets the name of the current working directory for the drive
indicated by drive.

drive ?Specifies a drive number (0 = default, 1 = A, etc.)
directory ?Points to an area of memory (of length MAXDIR) where the
?null-terminated directory name will be placed. The name
?does not contain the drive specification and does not begin
?with a backslash.

Return Value
?On success, returns 0
?On error, returns -1


Example:

#include <dir.h>
#include <stdio.h>
#include <string.h>

char *current_directory(char *path)
{
strcpy(path, "X:\\"); /* fill string with form of response: X:\ */
path[0] = 'A' + getdisk(); /* replace X with current drive letter */
getcurdir(0, path+3); /* fill rest of string with current directory */
return(path);
}

int main(void)
{
char curdir[MAXPATH];

current_directory(curdir);
printf("The current directory is %s\n", curdir);

return 0;
}
ma100 2005-10-19
  • 打赏
  • 举报
回复
getcurdir
megaboy 2005-10-19
  • 打赏
  • 举报
回复
用int main(int argc, char ** argv)


argv[0]就是包含运行exe文件时该文件所在绝对路径的字符串了。

33,321

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧