I used to make fopen safer with this code
fin = fopen(ifp, "r");
fout = fopen(ofp, "w");
if ((fin == NULL)||(fout == NULL))
printf ("Error opening files");
else {} //action
Now I moved to Microsoft Visual Studio 2013. It asks me to use fopen_s instead of fopen. Is there any solution other than using _CRT_SECURE_NO_WARNINGS? I mean, is the fact of filepath input (scanf) compatible with fopen_s? Or just forget it and disable security warnings?
P. S. I know that filepath input can be unsafe but I just have to do it this way, because it is stated so in my task.
I don't think this makes it safer. This is just good handling of conditions and what you should be doing. Probably should check errno
too.
That being said, if you have the ability to use fopen_s
, then I would use it. From MSDN on the "security enhancements":
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.