[英]Cross-platform way to get all files in directory in C++ besides boost
[英]What is a cross-platform way to get the current directory?
我需要一種跨平台的方式來獲取當前的工作目錄(是的,getcwd 做了我想要的)。 我認為這可能會奏效:
#ifdef _WIN32
#include <direct.h>
#define getcwd _getcwd // stupid MSFT "deprecation" warning
#elif
#include <unistd.h>
#endif
#include <string>
#include <iostream>
using namespace std;
int main()
{
string s_cwd(getcwd(NULL,0));
cout << "CWD is: " << s_cwd << endl;
}
我得到了這個閱讀:
應該沒有 memory 泄漏,它也應該在 Mac 上工作,對嗎?
更新:我擔心這里仍然有問題(我試圖避免創建一個具有確定長度的 char 數組,因為沒有適當的方法來為 getcwd 獲得合適的長度):
char* a_cwd = getcwd(NULL,0);
string s_cwd(a_cwd);
free(a_cwd); // or delete a_cwd?
如果您包含沒有問題,請使用boost filesystem進行方便的跨平台文件系統操作。
boost::filesystem::path full_path( boost::filesystem::current_path() );
這是一個例子。
編輯:正如 Roi Danton 在評論中指出的那樣,文件系統成為C++17 中 ISO C++ 的一部分,因此不再需要提升:
std::filesystem::current_path();
您不能使用 NULL 緩沖區調用getcwd
。 根據開放組:
如果 buf 是 null 指針,則未指定 getcwd() 的行為。
此外,getcwd 可以返回 NULL,這可以破壞字符串構造函數。
您需要將其更改為:
char buffer[SIZE];
char *answer = getcwd(buffer, sizeof(buffer));
string s_cwd;
if (answer)
{
s_cwd = answer;
}
使用 NULL 指針調用getcwd是實現定義的。 它通常使用 malloc 為您分配(在這種情況下,您的代碼確實存在 memory 泄漏)。 但是,它根本不能保證工作。 所以你應該分配你自己的緩沖區。
char *cwd_buffer = malloc(sizeof(char) * max_path_len);
char *cwd_result = getcwd(cwd_buffer, max_path_len);
Open Group 有一個示例展示如何從 _PC_PATH_MAX 獲取最大路徑長度。 您可以考慮在 Windows 上使用MAX_PATH 。 有關兩個平台上此數字的注意事項,請參閱此問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.