C++ 如何找到当前目录?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4807629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I find the current directory?
提问by lital maatuk
I am trying to read a file which I read previously successfully. I am reading it through a library, and I am sending it as-is to the library (i.e. "myfile.txt"). I know that the file is read from the working/current directory.
我正在尝试读取我之前成功读取的文件。我正在通过图书馆阅读它,并将其按原样发送到图书馆(即“myfile.txt”)。我知道该文件是从工作/当前目录中读取的。
I suspect that the current/working directory has changed somehow. How do i check what is the current/working directory?
我怀疑当前/工作目录以某种方式改变了。我如何检查当前/工作目录是什么?
回答by monoceres
Since you added the visual-c++ tag I'm going to suggest the standard windows function to do it. GetCurrentDirectory
由于您添加了visual-c++ 标记,因此我将建议使用标准的windows 函数来执行此操作。获取当前目录
Usage:
用法:
TCHAR pwd[MAX_PATH];
GetCurrentDirectory(MAX_PATH,pwd);
MessageBox(NULL,pwd,pwd,0);
回答by Dr G
回答by rubenvb
Here's the most platform-agnostic answer I got a while ago:
这是我不久前得到的最与平台无关的答案:
How return a std::string from C's "getcwd" function
如何从 C 的“getcwd”函数返回 std::string
It's pretty long-winded, but does exactly what it's supposed to do, with a nice C++ interface (ie it returns a string, not a how-long-are-you-exactly?-(const
) char*
).
它非常冗长,但它确实完成了它应该做的事情,有一个漂亮的 C++ 接口(即它返回一个字符串,而不是你的确切长度?-( const
) char*
)。
To shut up MSVC warnings about deprecation of getcwd
, you can do a
要关闭有关弃用的 MSVC 警告getcwd
,您可以执行以下操作
#if _WIN32
#define getcwd _getcwd
#endif // _WIN32
回答by IluxaKuk
This code works for Linux and Windows:
此代码适用于 Linux 和 Windows:
#include <stdio.h> // defines FILENAME_MAX
#include <unistd.h> // for getcwd()
#include <iostream>
std::string GetCurrentWorkingDir();
int main()
{
std::string str = GetCurrentWorkingDir();
std::cout << str;
return 0;
}
std::string GetCurrentWorkingDir()
{
std::string cwd("##代码##",FILENAME_MAX+1);
return getcwd(&cwd[0],cwd.capacity());
}