mirror of
https://github.com/fmtlib/fmt.git
synced 2025-09-12 06:03:56 -04:00
refactor: throw exception on fopen failure in safe_fopen
This commit is contained in:
parent
abaf452026
commit
00a1736307
24
test/util.h
24
test/util.h
@ -9,6 +9,12 @@
|
||||
#include <cstdio>
|
||||
#include <locale>
|
||||
#include <string>
|
||||
#include <stdexcept>
|
||||
#include <cerrno>
|
||||
#include <cstring>
|
||||
|
||||
|
||||
|
||||
|
||||
#include "fmt/os.h"
|
||||
|
||||
@ -31,14 +37,24 @@ extern const char* const file_content;
|
||||
// Opens a buffered file for reading.
|
||||
auto open_buffered_file(FILE** fp = nullptr) -> fmt::buffered_file;
|
||||
|
||||
inline auto safe_fopen(const char* filename, const char* mode) -> FILE* {
|
||||
inline FILE* safe_fopen(const char* filename, const char* mode) {
|
||||
#if defined(_WIN32) && !defined(__MINGW32__)
|
||||
// Fix MSVC warning about "unsafe" fopen.
|
||||
FILE* f = nullptr;
|
||||
errno = fopen_s(&f, filename, mode);
|
||||
int err = fopen_s(&f, filename, mode);
|
||||
if (err != 0 || f == nullptr) {
|
||||
throw std::runtime_error(
|
||||
std::string("cannot open file ") + filename + ": " + std::strerror(err)
|
||||
);
|
||||
}
|
||||
return f;
|
||||
#else
|
||||
return std::fopen(filename, mode);
|
||||
FILE* f = std::fopen(filename, mode);
|
||||
if (f == nullptr) {
|
||||
throw std::runtime_error(
|
||||
std::string("cannot open file ") + filename + ": " + std::strerror(errno)
|
||||
);
|
||||
}
|
||||
return f;
|
||||
#endif
|
||||
}
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user