獲取工作路徑這里介紹兩種方法:
1.使用getcwd()函數(shù)。
頭文件:#include <unistd.h>
定義函數(shù):char * getcwd(char * buf, size_t size);
函數(shù)說明:getcwd()會(huì)將當(dāng)前的工作目錄絕對路徑復(fù)制到參數(shù)buf 所指的內(nèi)存空間,參數(shù)size 為buf 的空間大小
實(shí)例:
void getPath(){ char pPath[256] = {0}; getcwd(buf, 256); printf("filePath: %s/n", pPath);}主函數(shù)調(diào)用此函數(shù)運(yùn)行結(jié)果:
filePath: /home/myTest
2.使用readlink()函數(shù)。
頭文件:#include <unistd.h>
函數(shù)定義:int readlink(const char *path, char *buf, size_t bufsiz);
函數(shù)說明:此函數(shù)會(huì)將參數(shù)path的符號連接內(nèi)容到參數(shù)buf所指的內(nèi)存空間,返回的內(nèi)容不是以NULL作字符串結(jié)尾,但會(huì)將字符串的字符數(shù)返回。若參數(shù)bufsiz小于符號連接的內(nèi)容長度,過長的內(nèi)容會(huì)被截?cái)唷3晒Ψ祷豣uf長度,失敗返回 -1.
實(shí)例:
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();}運(yùn)行結(jié)果:
the file Path: /home/myTest/a.out
以上這篇linux 下獲取當(dāng)前工作路徑的實(shí)例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選