日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C++?getcwd函數獲取項目運行路徑方法詳解_C 語言

作者:cpp_learners ? 更新時間: 2022-11-21 編程語言

頭文件:

在unix下是unistd.h,VS下是direct.h

代碼:

#include <stdio.h>
#include <string>
// 區分此函數是在Windows環境調用還是Linux環境調用
#if defined (_WIN64) || defined (WIN32) || defined (_WIN32)
//printf("---Windows---\n");
#include <direct.h>
#else
//printf("---Linux---\n");
#include <unistd.h>
#endif
/******************************************************************************
 *
 * 功能:
 *		獲得當前程序的工作路徑(絕對路徑),即運行路徑!
 *
 * 注意:
 *		頭文件在unix下是unistd.h,VS下是direct.h,應該依編程者的環境而定.
 *		這里解釋一下運行路徑,即是程序開始運行的路徑,例如:
 *			1.如果是在Windows環境的VS編譯器中運行項目,則返回的是項目路徑,
 *			  即代碼文件路徑(.h和.cpp路徑),因為是在編譯器中運行的項目,所以
 *			  程序的運行路徑也是才項目路徑中開始運行的。
 *			2.如果是在Windows環境,運行已經編譯好的.exe程序,則返回的是當前
 *			  .exe程序所在的路徑,因為是在當前路徑所運行的!
 *			3.在Linux環境,返回的都是可執行程序的路徑!
 *
 * 參數:
 *		無.
 *
 * 返回值:
 *		成功返回程序的工作路徑(絕對路徑);失敗返回空串
 *
 ******************************************************************************/
std::string getOperationFilePath() {
	char *buffer = NULL;
	// 區分此函數是在Windows環境調用還是Linux環境調用
#if defined (_WIN64) || defined (WIN32) || defined (_WIN32)
	// 獲取項目的工作路徑
	buffer = _getcwd(NULL, 0);
#else
	// 獲取項目的工作路徑
	buffer = getcwd(NULL, 0);
#endif
	if (buffer) {
		std::string path = buffer;
		free(buffer);
		return path ;
	}
	return "";
}

測試運行:

int main(void) {
	printf("getOperationFilePath = %s\n", getOperationFilePath().c_str());
	system("pause");
	return 0;
}

在VS中運行截圖:

直接運行.exe截圖:

解釋上面提到的問題:

這里解釋一下運行路徑,即是程序開始運行的路徑,例如:

  • 如果是在Windows環境的VS編譯器中運行項目,則返回的是項目路徑,即代碼文件路徑(.h和.cpp路徑),因為是在編譯器中運行的項目,所以程序的運行路徑也是才項目路徑中開始運行的。
  • 如果是在Windows環境,運行已經編譯好的.exe程序,則返回的是當前.exe程序所在的路徑,因為是在當前路徑所運行的!
  • 在Linux環境,返回的都是可執行程序的路徑!

Windows有一個api可以直接獲得項目的運行路徑,不用區分是在項目中運行還是.exe運行!

頭文件:

#include < Windows.h >

#include <Windows.h>
int main(void) {
	char path[1024] = { 0 };
	GetModuleFileNameA(NULL, path, MAX_PATH);		// 獲取到完整路徑,如:E:\Tools\qq.exe
	*strrchr(path, '\\') = '\0';					// 截取路徑,如:E:\Tools
	printf("paht = %s\n", path);
	system("pause");
	return 0;
}

運行截圖:

如果把代碼:*strrchr(path, ‘\’) = ‘\0’; // 截取路徑,如:E:\Tools

注釋掉,則可以獲得全路徑:

如果第一種方式沒法正確獲取的話,可以嘗試使用此種方式:

頭文件: #include < unistd.h >

linux系統中有個符號鏈接:/proc/self/exe它代表當前程序,可以用readlink讀取它的源路徑就可以獲取當前程序的絕對路徑了。

std::string getOperationFilePath() {
    char buf[256] = { 0 };
    int ret = readlink("/proc/self/exe", buf, 256);
    if (ret < 0) {
        printf("%d: readlink error:%s", __LINE__, strerror(errno));
        return "";
    }
    *strrchr(buf, '/') = '\0';      // 去掉可執行程序名  /tmp/test/a.exe    ==>     /tmp/test
    return buf;
}

總結:

這也是一個小小的細節問題,也有點小坑,今天這個坑我踩過,下次就不會再踩了。

原文鏈接:https://blog.csdn.net/cpp_learner/article/details/123424715

欄目分類
最近更新