linux 下获取当前工作路径的方法
2017-04-18 14:49
435 查看
获取工作路径这里介绍两种方法:
1.使用getcwd()函数。
头文件:#include <unistd.h>
定义函数:char * getcwd(char * buf, size_t size);
函数说明:getcwd()会将当前的工作目录绝对路径复制到参数buf 所指的内存空间,参数size 为buf 的空间大小
实例:
void getPath()
{
char pPath[256] = {0};
getcwd(buf, 256);
printf("filePath: %s\n", pPath);
}
主函数调用此函数运行结果:
filePath: /home/myTest
2.使用readlink()函数。
头文件:#include <unistd.h>
函数定义:int readlink(const char *path, char *buf, size_t bufsiz);
函数说明:此函数会将参数path的符号连接内容到参数buf所指的内存空间,返回的内容不是以NULL作字符串结尾,但会将字符串的字符数返回。若参数bufsiz小于符号连接的内容长度,过长的内容会被截断。成功返回buf长度,失败返回 -1.
实例:
void getPath()
{
char pPath[256] = {0};
int ret = -1;
ret = readlink("/proc/self/exe", pPath, 256);
pPath[ret] = "\0"
printf("the file Path: %s\n", pPath);
}
int main()
{
getPath();
}
运行结果:
the file Path: /home/myTest/a.out
1.使用getcwd()函数。
头文件:#include <unistd.h>
定义函数:char * getcwd(char * buf, size_t size);
函数说明:getcwd()会将当前的工作目录绝对路径复制到参数buf 所指的内存空间,参数size 为buf 的空间大小
实例:
void getPath()
{
char pPath[256] = {0};
getcwd(buf, 256);
printf("filePath: %s\n", pPath);
}
主函数调用此函数运行结果:
filePath: /home/myTest
2.使用readlink()函数。
头文件:#include <unistd.h>
函数定义:int readlink(const char *path, char *buf, size_t bufsiz);
函数说明:此函数会将参数path的符号连接内容到参数buf所指的内存空间,返回的内容不是以NULL作字符串结尾,但会将字符串的字符数返回。若参数bufsiz小于符号连接的内容长度,过长的内容会被截断。成功返回buf长度,失败返回 -1.
实例:
void getPath()
{
char pPath[256] = {0};
int ret = -1;
ret = readlink("/proc/self/exe", pPath, 256);
pPath[ret] = "\0"
printf("the file Path: %s\n", pPath);
}
int main()
{
getPath();
}
运行结果:
the file Path: /home/myTest/a.out
相关文章推荐
- linux 获取当前工作路径
- linux 下获取当前工作路径的实例
- c语言获取当前工作路径的实现代码(windows/linux)
- Linux中获取当前程序路径的方法
- C++文件操作——获取当前工作路径的几种方法
- Linux中shell脚本获取当前工作目录的方法
- Linux中获取当前程序路径的方法
- Windows和Linux下获取当前可执行文件路径和工作目录
- Java在不同环境下获取当前路径的方法--this.getClass().getResource("")
- 三种方法可以获取当前web程序目录物理路径
- 解析Linux内核获取当前进程指针的方法 [原]
- 【转】C#获取当前路径的方法集合
- [导入]C#中获取程序当前路径的集中方法
- C#中获取当前路径的几种方法
- C#中获取当前路径的几种方法
- EVC获取当前工作路径
- Java在不同环境下获取当前路径的方法--this.getClass().getResource("")
- C#获取当前路径的方法集合
- C#中获取当前路径的几种方法
- C#获取程序当前路径的方法