gpt4 book ai didi

c - 当我需要请求文件路径时如何使用 fopen_s?

转载 作者:太空宇宙 更新时间:2023-11-04 03:48:32 25 4
gpt4 key购买 nike

我曾经使用这段代码使 fopen 更安全

fin = fopen(ifp, "r");
fout = fopen(ofp, "w");
if ((fin == NULL)||(fout == NULL))
printf ("Error opening files");
else {} //action

现在我转到 Microsoft Visual Studio 2013。它要求我使用 fopen_s 而不是 fopen。除了使用 _CRT_SECURE_NO_WARNINGS 之外还有其他解决方案吗?我的意思是,文件路径输入 (scanf) 是否与 fopen_s 兼容?或者干脆忘记它并禁用安全警告?

P. S. 我知道文件路径输入可能是不安全的,但我只能这样做,因为我的任务中是这样规定的。

最佳答案

我不认为这会使它更安全。这只是对条件的良好处理以及您应该做的事情。可能也应该检查 errno

也就是说,如果您有能力使用fopen_s,那么我会使用它。来自“security enhancements”上的 MSDN:

  • Parameter Validation . Parameters passed to CRT functions are validated, in both secure functions and in many preexisting versions of functions. These validations include:

    • Checking for NULL values passed to the functions.

    • Checking enumerated values for validity.

    • Checking that integral values are in valid ranges.

    For more information, see Parameter Validation.

  • A handler for invalid parameters is also accessible to the developer. When an encountering an invalid parameter, instead of asserting and exiting the application, the CRT provides a way to check these problems with the _set_invalid_parameter_handler function.

  • Sized Buffers . The secure functions require that the buffer size be passed to any function that writes to a buffer. The secure versions validate that the buffer is large enough before writing to it, helping to avoid dangerous buffer overrun errors that could allow malicious code to execute. These functions usually return an errno type of error code and invoke the invalid parameter handler if the size of the buffer is too small. Functions that read from input buffers, such as gets, have secure versions that require you to specify a maximum size.

  • Null termination . Some functions that left potentially non-terminated strings have secure versions which ensure that strings are properly null terminated.

  • Enhanced error reporting . The secure functions return error codes with more error information than was available with the preexisting functions. The secure functions and many of the preexisting functions now set errno and often return an errno code type as well, to provide better error reporting.

  • Filesystem security . Secure file I/O APIs support secure file access in the default case.

  • Windows security . Secure process APIs enforce security policies and allow ACLs to be specified.

  • Format string syntax checking . Invalid strings are detected, for example, using incorrect type field characters in printf format strings.

关于c - 当我需要请求文件路径时如何使用 fopen_s?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22533292/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com