change sopen_s to wsopen_s (fmtlib#3234)

This commit is contained in:
Fros1er 2023-02-06 14:11:21 +08:00
parent 05e3a9233a
commit 4c4389589b
5 changed files with 39 additions and 1 deletions

View File

@ -337,6 +337,11 @@ class FMT_API file {
// Creates a buffered_file object associated with this file and detaches
// this file object from the file.
buffered_file fdopen(const char* mode);
# if defined(_WIN32) && !defined(__MINGW32__)
// Opens a file and constructs a file object representing this file by wcstring_view filename. Windows only.
static file open_windows_file(wcstring_view path, int oflag);
#endif
};
// Returns the memory page size.

View File

@ -221,7 +221,8 @@ file::file(cstring_view path, int oflag) {
S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
# if defined(_WIN32) && !defined(__MINGW32__)
fd_ = -1;
FMT_POSIX_CALL(sopen_s(&fd_, path.c_str(), oflag, _SH_DENYNO, mode));
auto converted = detail::utf8_to_utf16(string_view(path.c_str()));
FMT_POSIX_CALL(wsopen_s(&fd_, converted.c_str(), oflag, _SH_DENYNO, mode));
# else
FMT_RETRY(fd_, FMT_POSIX_CALL(open(path.c_str(), oflag, mode)));
# endif
@ -353,6 +354,20 @@ buffered_file file::fdopen(const char* mode) {
return bf;
}
# if defined(_WIN32) && !defined(__MINGW32__)
file file::open_windows_file(wcstring_view path, int oflag) {
int fd_ = -1;
using mode_t = int;
constexpr mode_t mode =
S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
FMT_POSIX_CALL(wsopen_s(&fd_, path.c_str(), oflag, _SH_DENYNO, mode));
if (fd_ == -1)
FMT_THROW(system_error(errno, FMT_STRING("cannot open file {}"),
detail::utf16_to_utf8(path.c_str()).c_str()));
return file(fd_);
}
# endif
long getpagesize() {
# ifdef _WIN32
SYSTEM_INFO si;

View File

@ -127,6 +127,17 @@ TEST(os_test, report_windows_error) {
fmt::to_string(out));
}
# if FMT_USE_FCNTL && !defined(__MINGW32__)
TEST(file_test, open_windows_file) {
using fmt::file;
file out = file::open_windows_file(L"test-file",
file::WRONLY | file::CREATE | file::TRUNC);
out.write("x", 1);
file in = file::open_windows_file(L"test-file", file::RDONLY);
EXPECT_READ(in, "x");
}
# endif // FMT_USE_FCNTL && !defined(__MINGW32__)
#endif // _WIN32
#if FMT_USE_FCNTL

View File

@ -78,6 +78,11 @@ errno_t test::sopen_s(int* pfh, const char* filename, int oflag, int shflag,
EMULATE_EINTR(open, EINTR);
return _sopen_s(pfh, filename, oflag, shflag, pmode);
}
errno_t test::wsopen_s(int* pfh, const wchar_t* filename, int oflag, int shflag,
int pmode) {
EMULATE_EINTR(open, EINTR);
return _wsopen_s(pfh, filename, oflag, shflag, pmode);
}
#endif
#ifndef _WIN32

View File

@ -39,6 +39,8 @@ typedef unsigned size_t;
typedef int ssize_t;
errno_t sopen_s(int* pfh, const char* filename, int oflag, int shflag,
int pmode);
errno_t wsopen_s(int* pfh, const wchar_t* filename, int oflag, int shflag,
int pmode);
#endif
#ifndef _WIN32