Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)
(시리즈 글이 3개 있습니다.)
C/C++: 178. C++ - 파일에 대한 Text 모드의 "translated" 동작
; https://www.sysnet.pe.kr/2/0/13766

C/C++: 179. C++ - _O_WTEXT, _O_U16TEXT, _O_U8TEXT의 Unicode stream 모드
; https://www.sysnet.pe.kr/2/0/13768

C/C++: 180. C++ - 고수준 FILE I/O 함수에서의 Unicode stream 모드(_O_WTEXT, _O_U16TEXT, _O_U8TEXT)
; https://www.sysnet.pe.kr/2/0/13776




C++ - 고수준 FILE I/O 함수에서의 Unicode stream 모드(_O_WTEXT, _O_U16TEXT, _O_U8TEXT)

이전에 _O_WTEXT, _O_U16TEXT, _O_U8TEXT 옵션에서만 가능한 Unicode 모드를 살펴봤는데요,

C++ - _O_WTEXT, _O_U16TEXT, _O_U8TEXT의 Unicode stream 모드
; https://www.sysnet.pe.kr/2/0/13768

위의 글에서는 저수준의 file I/O 함수를 사용한 것이고, 이번에는 FILE을 사용한 Stream 방식의 I/O 함수로 다뤄보겠습니다. FILE의 경우, fopen 함수에는 저수준의 _O_??? 상숫값들을 직접 받을 수 있는 인자가 없고, 대신 그것들을 표현하는 문자열만 가능합니다.

errno_t fopen_s(FILE** pFile, const char *filename, const char *mode);

errno_t _wfopen_s(FILE** pFile, const wchar_t *filename, const wchar_t *mode);

Visual C++는 _O_WTEXT, _O_U16TEXT, _O_U8TEXT 모드에 각각 대응하는 문자열을 새롭게 추가를 했는데요, 그래서 도입된 것이 "ccs" 옵션입니다.

  • _O_WTEXT: "ccs=UNICODE"
  • _O_U16TEXT: "ccs=UTF-16LE"
  • _O_U8TEXT: "ccs=UTF-8"

이 외에 전체적인 규칙은 같습니다. 단지, 차이점이라면 유니코드 모드로 파일을 여는 경우 wchar_t 정렬로 데이터 I/O를 하지 않았을 때,

#include <iostream>

int main()
{
    FILE* fs;
    fopen_s(&fs, "test_utf16", "w+, ccs=UTF-16LE");
    fputs("test", fs);
    fclose(fs);
}

디버그 모드로 실행 시 이런 assertion 에러가 발생합니다. (만약 release 모드라면 crash와 함께 이벤트 뷰어에 기록이 남습니다.)

Debug Assertion Failed!

Program: ...u8text_u16text\unicode_mode\x64\Debug\ConsoleApplication1.exe
File: minkernel\crts\ucrt\src\appcrt\stdio\fputs.cpp
Line: 20

Expression: ( (_Stream.is_string_backed()) || (fn = _fileno(_Stream.public_stream()), ((_textmode_safe(fn) == __crt_lowio_text_mode::ansi) && !_tm_unicode_safe(fn))))

Low level File I/O에서는 "buffer_size % 2 == 0"라는 메시지가 발생했던 것과는... 뭐랄까 직관적으로 오류 원인을 파악하기 힘든 내용입니다.




제가 이전 글에서, _O_WTEXT의 사용을 권장하지 않았는데요, 이게 고수준 File I/O 함수에서도 마찬가지로 혼란을 야기할 수 있습니다. 예를 들어, ccs=UNICODE는,

// C:\Program Files (x86)\Windows Kits\10\Source\10.0.22621.0\ucrt\inc\corecrt_internal_stdio.h

template <typename Character>
__acrt_stdio_stream_mode __cdecl __acrt_stdio_parse_mode(
    Character const* const mode
    ) throw()
{
    // ...[생략]...

    // Otherwise, we saw the beginning of an encoding; parse it:
    static Character const ccs[]              = { 'c', 'c', 's' };
    static Character const utf8_encoding[]    = { 'U', 'T', 'F', '-', '8' };
    static Character const utf16_encoding[]   = { 'U', 'T', 'F', '-', '1', '6', 'L', 'E' };
    static Character const unicode_encoding[] = { 'U', 'N', 'I', 'C', 'O', 'D', 'E' };

    // ...[생략]...

    if (stdio_traits::tcsnicmp(it, utf8_encoding, _countof(utf8_encoding)) == 0)
    {
        it += _countof(utf8_encoding);
        result._lowio_mode |= _O_U8TEXT;
    }
    else if (stdio_traits::tcsnicmp(it, utf16_encoding, _countof(utf16_encoding)) == 0)
    {
        it += _countof(utf16_encoding);
        result._lowio_mode |= _O_U16TEXT;
    }
    else if (stdio_traits::tcsnicmp(it, unicode_encoding, _countof(unicode_encoding)) == 0)
    {
        it += _countof(unicode_encoding);
        result._lowio_mode |= _O_WTEXT;
    }
    else
    {
        _VALIDATE_RETURN(("Invalid file open mode", 0), EINVAL, result);
    }

    // ...[생략]...
}

분명히 _O_WTEXT 모드로 파일을 열게 되는 것과 같습니다. 그런데, 해당 모드로 Low Level에서와 High Level에서 파일을 열었을 때 출력 결과가 다릅니다.

예를 들어, 다음과 같이 2개의 파일을 생성해 보면,

{
    FILE* fs;
    fopen_s(&fs, "test_unicode.txt", "w+, ccs=UNICODE");
    const wchar_t text[] = L"test";
    fputws(text, fs);
    fclose(fs);
}

{
    int fd = 0;
    _sopen_s(&fd, "test_unicode_ll.txt", _O_CREAT | _O_WRONLY | _O_TRUNC | _O_WTEXT, _SH_DENYNO, _S_IWRITE);

    const wchar_t* text = L"test"; // 0xd803,0xdc80 == U+10C80
    _write(fd, text, wcslen(text) * sizeof(wchar_t));
    _close(fd);
}

High Level로 열은, 즉 fopen_s + ccs=UNICODE 옵션의 파일은 ASCII 포맷으로 저장이 되고,

c:\temp> powershell Format-Hex -Path test_unicode.txt

           Path: C:\temp\test_unicode.txt

           00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F

00000000   74 65 73 74                                      test

Low Level로 열은, 즉 _sopen_s + _O_WTEXT 옵션의 파일은 UTF-16LE 포맷으로 저장이 됩니다.

00000000   FF FE 74 00 65 00 73 00 74 00                    .þt.e.s.t.

역시 혼란스럽죠? ^^; 게다가 "test_unicode.txt" 파일에 대해 _setmode로 신규 모드를 설정했을 때 반환하는 값은 _O_TEXT(0x4000) 모드로 나옵니다.

FILE* fs;
fopen_s(&fs, "test_unicode.txt", "w+, ccs=UNICODE");
int old_mode = _setmode(_fileno(fs), _O_WTEXT);
std::cout << "old_mode: 0x" << std::hex << old_mode << std::endl;

/* 출력 결과:
old_mode: 0x4000
*/

_O_TEXT 모드로 나온다는 결과는 이전의 저수준 I/O 결과와 동일해 일관성이 있다는 측면이 있지만, 그렇다면 오히려 "test_unicode.txt" 파일에는 ANSI로 출력되었어야 하는데 UTF-16으로 출력을 하고 있는 것입니다.

그러니까, 이것 역시 개인적으로는 ccs=UNICODE 옵션을 사용하지 않는 것을 권장합니다. (엄밀히 결과 파일로만 놓고 봤을 때는 ccs=UNICODE 옵션은 잘 작동하고 있다고 볼 수 있습니다.)




참고로, 이해를 돕기 위해 _O_U8TEXT, _O_U16TEXT에 대한 파일 I/O 예제를 C# 코드로 대응시키면 다음과 같습니다.

using System.Text;

internal class Program
{
    static void Main(string[] args)
    {
        string text = "test한";

        // _O_U8TEXT
        {
            using (FileStream fs = new FileStream("test_utf8.txt", FileMode.Truncate))
            using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8))
            {
                sw.Write(text);
            }
        }

        // _O_U16TEXT
        {
            using (FileStream fs = new FileStream("test_utf16le.txt", FileMode.Truncate))
            using (StreamWriter sw = new StreamWriter(fs, Encoding.Unicode))
            {
                sw.Write(text);
            }
        }
    }
}




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 10/28/2024]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 16  17  18  19  20  [21]  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13413정성태9/14/202311968닷넷: 2143. C# - 시스템 Time Zone 변경 시 이벤트 알림을 받는 방법
13412정성태9/14/202315479닷넷: 2142. C# 12 - 인라인 배열(Inline Arrays) [1]
13411정성태9/12/202311794Windows: 252. 권한 상승 전/후 따로 관리되는 공유 네트워크 드라이브 정보 [1]
13410정성태9/11/202313271닷넷: 2141. C# 12 - Interceptor (컴파일 시에 메서드 호출 재작성) [1]
13409정성태9/8/202312548닷넷: 2140. C# - Win32 API를 이용한 모니터 전원 끄기
13408정성태9/5/202312126Windows: 251. 임의로 만든 EXE 파일을 포함한 ZIP 파일의 압축을 해제할 때 Windows Defender에 의해 삭제되는 경우
13407정성태9/4/202311959닷넷: 2139. C# - ParallelEnumerable을 이용한 IEnumerable에 대한 병렬 처리
13406정성태9/4/202311736VS.NET IDE: 186. Visual Studio Community 버전의 라이선스
13405정성태9/3/202312824닷넷: 2138. C# - async 메서드 호출 원칙
13404정성태8/29/202312984오류 유형: 876. Windows - 키보드의 등호(=, Equals sign) 키가 눌리지 않는 경우
13403정성태8/21/202311639오류 유형: 875. The following signatures couldn't be verified because the public key is not available: NO_PUBKEY EB3E94ADBE1229CF
13402정성태8/20/202311846닷넷: 2137. ILSpy의 nuget 라이브러리 버전 - ICSharpCode.Decompiler
13401정성태8/19/202311756닷넷: 2136. .NET 5+ 환경에서 P/Invoke의 성능을 높이기 위한 SuppressGCTransition 특성 [1]
13400정성태8/10/202311458오류 유형: 874. 파이썬 - pymssql을 윈도우 환경에서 설치 불가
13399정성태8/9/202310425닷넷: 2135. C# - 지역 변수로 이해하는 메서드 매개변수의 값/참조 전달
13398정성태8/3/202313409스크립트: 55. 파이썬 - pyodbc를 이용한 SQL Server 연결 사용법
13397정성태7/23/202312395닷넷: 2134. C# - 문자열 연결 시 string.Create를 이용한 GC 할당 최소화
13396정성태7/22/202311815스크립트: 54. 파이썬 pystack 소개 - 메모리 덤프로부터 콜 스택 열거
13395정성태7/20/202311086개발 환경 구성: 685. 로컬에서 개발 중인 ASP.NET Core/5+ 웹 사이트에 대해 localhost 이외의 호스트 이름으로 접근하는 방법
13394정성태7/16/202310441오류 유형: 873. Oracle.ManagedDataAccess.Client - 쿼리 수행 시 System.InvalidOperationException
13393정성태7/16/202311163닷넷: 2133. C# - Oracle 데이터베이스의 Sleep 쿼리 실행하는 방법
13392정성태7/16/202310765오류 유형: 872. Oracle - ORA-01031: insufficient privileges
13391정성태7/14/202311146닷넷: 2132. C# - sealed 클래스의 메서드를 callback 호출했을 때 인라인 처리가 될까요?
13390정성태7/12/202311085스크립트: 53. 파이썬 - localhost 호출 시의 hang 현상
13389정성태7/5/202311451개발 환경 구성: 684. IIS Express로 호스팅하는 웹을 WSL 환경에서 접근하는 방법
13388정성태7/3/202311872오류 유형: 871. 윈도우 탐색기에서 열리지 않는 zip 파일 - The Compressed (zipped) Folder '[...].zip' is invalid. [1]파일 다운로드1
... 16  17  18  19  20  [21]  22  23  24  25  26  27  28  29  30  ...