windows open() 函数的 _sopen_s() 等价物是什么?

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

What is the _sopen_s() equivalent for the open() function?

c++cwindows

提问by user281806

Microsoft has deprecated _open in favor of _sopen_s. What are the recommended equivalent arguments?

Microsoft 已弃用 _open 以支持 _sopen_s。推荐的等效参数是什么?

回答by user281806

Well now I can post my nicely formatted answer, so here it is:

那么现在我可以发布我的格式很好的答案,所以这里是:

For

为了

int fd = _open(name,oflags);

Replace with

用。。。来代替

int fd;
errno_t errno = _sopen_s(&fd,name,oflags,_SH_DENYNO,0);

The reason I posted this Q&A is that it provides an important bit of non-obvious info that Microsoft didn't provide. I agree that the _sopen_s is a poor replacement for _open. I only researched this topic because I was fixing a bug caused by the wrong arguments being supplied to _sopen_s. The _sopen_s was only in the code to get rid of the compiler warnings; the original _open call was fine.

我发布此问答的原因是它提供了 Microsoft 没有提供的一些重要的非显而易见的信息。我同意 _sopen_s 是 _open 的糟糕替代品。我只研究了这个主题,因为我正在修复由提供给 _sopen_s 的错误参数引起的错误。_sopen_s 只是在代码中去除编译器警告;最初的 _open 调用很好。

回答by R.. GitHub STOP HELPING ICE

The best recommendation is ignoring all of Microsoft's politically motivateddeprecations. Their "safe" functions offer no actual safety advantages over correct use of the existing, standard C or POSIX-like functions, and if used incorrectly, they are just as "unsafe" as the functions they aim to replace.

最好的建议是忽略 Microsoft出于动机的所有弃用。与正确使用现有的标准 C 或 POSIX 类函数相比,它们的“安全”函数没有提供实际的安全优势,如果使用不当,它们与它们旨在替换的函数一样“不安全”。

回答by Valeri Atamaniouk

On Windows I suggest to use CreateFileunless there is a good reason not to do so. On Linux "open" maps to kernel function, on Windows - to library function, that uses "CreateFile" anyway. As per portability, this function is somewhat more portable on Microsoft platforms (Win32/64/CE). And, naturally, not available on *nix.

在 Windows 上,我建议使用CreateFile,除非有充分的理由不这样做。在 Linux 上,“open”映射到内核函数,在 Windows 上映射到库函数,无论如何都使用“CreateFile”。根据可移植性,此功能在 Microsoft 平台(Win32/64/CE)上更具可移植性。而且,自然地,在 *nix 上不可用。