Reactos
1//
2// openfile.cpp
3//
4// Copyright (c) Microsoft Corporation. All rights reserved.
5//
6// Functions that open a file as a stdio stream, with mode and share flag.
7//
8#include <corecrt_internal_stdio.h>
9#include <sys/stat.h>
10
11
12
13// Opens a file with a string mode and file sharing flag. This function defines
14// the common logic shared by other stdio open functions. It parses the mode
15// string, per the rules described in the above parser, then opens the file via
16// the lowio library.
17//
18// Returns the new FILE* on success; returns nullptr on failure.
19template <typename Character>
20static FILE* __cdecl common_openfile(
21 Character const* const file_name,
22 Character const* const mode,
23 int const share_flag,
24 __crt_stdio_stream const stream
25 ) throw()
26{
27 typedef __acrt_stdio_char_traits<Character> stdio_traits;
28
29 _ASSERTE(file_name != nullptr);
30 _ASSERTE(mode != nullptr);
31 _ASSERTE(stream.valid());
32
33 __acrt_stdio_stream_mode const parsed_mode = __acrt_stdio_parse_mode(mode);
34 if (!parsed_mode._success)
35 return nullptr;
36
37 int fh;
38 if (stdio_traits::tsopen_s(&fh, file_name, parsed_mode._lowio_mode, share_flag, _S_IREAD | _S_IWRITE) != 0)
39 return nullptr;
40
41 // Ensure that streams get flushed during pre-termination:
42 #ifndef CRTDLL
43 _cflush++;
44 #endif
45
46 // Initialize the stream:
47 stream.set_flags(parsed_mode._stdio_mode);
48 stream->_cnt = 0;
49 stream->_tmpfname = nullptr;
50 stream->_base = nullptr;
51 stream->_ptr = nullptr;
52 stream->_file = fh;
53
54 return stream.public_stream();
55}
56
57
58
59extern "C" FILE* __cdecl _openfile(
60 char const* const file_name,
61 char const* const mode,
62 int const share_flag,
63 FILE* const public_stream
64 )
65{
66 return common_openfile(file_name, mode, share_flag, __crt_stdio_stream(public_stream));
67}
68
69extern "C" FILE* __cdecl _wopenfile(
70 wchar_t const* const file_name,
71 wchar_t const* const mode,
72 int const share_flag,
73 FILE* const public_stream
74 )
75{
76 return common_openfile(file_name, mode, share_flag, __crt_stdio_stream(public_stream));
77}