如何在C程序中获取当前目录?
我正在制作一个 C 程序,我需要获取该程序启动的目录。 该程序是为 UNIX 计算机编写的。 我一直在研究 opendir()
和 telldir()
,但是 telldir()
返回一个 off_t (long int)< /code>,所以它真的对我没有帮助。
如何获取字符串(字符数组)中的当前路径?
I'm making a C program where I need to get the directory that the program is started from. This program is written for UNIX computers. I've been looking at opendir()
and telldir()
, but telldir()
returns a off_t (long int)
, so it really doesn't help me.
How can I get the current path in a string (char array)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您是否看过
getcwd()
?简单的例子:
Have you had a look at
getcwd()
?Simple example:
查找手册页获取
getcwd.
另请参阅一篇关于过时
getwd
的文章以及一些路径处理常量,例如缓冲区大小限制。Look up the man page for
getcwd
.See also an article about the obsolete
getwd
and some path-handling constants like buffer size limits.尽管问题被标记为 Unix,但当目标平台是 Windows 时,人们也可以访问它,而 Windows 的答案是
GetCurrentDirectory()
function:
这些答案适用于 C 和 C++ 代码。
user4581301 在 对另一个问题的评论,并通过 Google 搜索“site:microsoft”验证为当前首选。 com getcurrentdirectory'。
Although the question is tagged Unix, people also get to visit it when their target platform is Windows, and the answer for Windows is the
GetCurrentDirectory()
function:
These answers apply to both C and C++ code.
Link suggested by user4581301 in a comment to another question, and verified as the current top choice with a Google search 'site:microsoft.com getcurrentdirectory'.
要获取当前目录(执行目标程序的位置),可以使用以下示例代码,该代码适用于 Visual Studio 和 Linux/MacOS(gcc/clang)、C 和 C++:
To get current directory (where you execute your target program), you can use the following example code, which works for both Visual Studio and Linux/MacOS(gcc/clang), both C and C++:
请注意,
getcwd(3)
也可在 Microsoft 的 libc 中使用:getcwd(3),其工作方式与您期望的相同。必须与
-lodnames
(oldnames.lib,在大多数情况下自动完成)链接,或使用_getcwd()
。 无前缀版本在 Windows RT 下不可用。Note that
getcwd(3)
is also available in Microsoft's libc: getcwd(3), and works the same way you'd expect.Must link with
-loldnames
(oldnames.lib, which is done automatically in most cases), or use_getcwd()
. The unprefixed version is unavailable under Windows RT.使用 getcwd
或
Use getcwd
OR