windows windows中_chdir和SetCurrentDirectory有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7544153/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 18:08:45  来源:igfitidea点击:

What is the difference between _chdir and SetCurrentDirectory in windows?

c++cwindowswinapi

提问by shawn

Are there any difference that I should choose one over the other?

我应该选择一个而不是另一个有什么区别吗?

回答by Uffe

They achieve the same result but belong to different APIs, so they return their results and report errors in different ways.

它们实现的结果相同,但属于不同的 API,因此它们返回结果并以不同的方式报告错误。

If you're already using other routines from either API, pick that one. If not, SetCurrentDirectory() is more "Windowsy", while _chdir() is more similar to the POSIX API. If you have a mind to port the code to, say, a Linux platform, use _chdir(); if you know you will only ever run the code on Windows platforms, SetCurrentDirectory().

如果您已经在使用任一 API 中的其他例程,请选择那个。如果不是,则 SetCurrentDirectory() 更“Windowsy”,而 _chdir() 更类似于 POSIX API。如果您想将代码移植到 Linux 平台,请使用 _chdir(); 如果你知道你只会在 Windows 平台上运行代码,SetCurrentDirectory()。

回答by eran

_chdiractually uses SetCurrentDirectoryinternally, so on most cases they are effectively interchangeable. However, _chdirdoes one more thing: it updates the current directory of the current drive, stored in an environment variable. This is needed, as the remark in _tchdirstates, because "other functions (fullpath, spawn, etc) need them to be set".

_chdir实际上在SetCurrentDirectory内部使用,因此在大多数情况下它们可以有效地互换。但是,还有_chdir一件事:它更新当前驱动器的当前目录,存储在环境变量中。这是必要的,正如_tchdir状态中的评论,因为“其他功能(完整路径、生成等)需要设置它们”。

I'm not sure how much this is needed these days, but I would say - if you're using those POSIX-style functions for file operations, path manipulation, process creation etc., use _chdiraccordingly. If you're using Win32 API functions directly, use SetCurrentDirectory.

我不确定这些天需要多少,但我想说 - 如果您将那些 POSIX 风格的函数用于文件操作、路径操作、进程创建等,请相应地使用_chdir。如果您直接使用 Win32 API 函数,请使用SetCurrentDirectory.

回答by IronMensan

SetCurrentDirectory is a macro that will resolve to SetCurrentDirectoryA or SetCurrentDirectoryW depending on the build settings. There is no system provided macro for _chdir and _wchdir.

SetCurrentDirectory 是一个宏,它将根据构建设置解析为 SetCurrentDirectoryA 或 SetCurrentDirectoryW。_chdir 和 _wchdir 没有系统提供的宏。

The MSDN page for SetCurrentDirectorystates that the argument can be relative to the current working directory or absolute. The documentation for _chdir does not say either way, though it seems that it does Can chdir() accept relative paths?on Linux.

SetCurrentDirectoryMSDN 页面指出该参数可以相对于当前工作目录或绝对目录。_chdir 的文档没有说任何一种方式,尽管它似乎可以 chdir() 接受相对路径吗?在 Linux 上。