Namespaces
Variants

std:: fwide

From cppreference.net
< cpp ‎ | io ‎ | c
ヘッダーで定義 <cwchar>
int fwide ( std:: FILE * stream, int mode ) ;

mode > 0 の場合、 stream をワイド指向に設定しようと試みます。 mode < 0 の場合、 stream をバイト指向に設定しようと試みます。 mode == 0 の場合、ストリームの現在の向きのみを問い合わせます。

ストリームの向きが既に決定されている場合(出力の実行または以前のfwideの呼び出しによる)、この関数は何もしません。

目次

パラメータ

stream - 変更または問い合わせを行うC I/Oストリームへのポインタ
mode - 0より大きい整数値でストリームをワイドに設定、0より小さい値でストリームをナローに設定、0の場合は問い合わせのみを行う

戻り値

この呼び出し後にストリームがワイド指向である場合はゼロより大きい整数、バイト指向である場合はゼロより小さい整数、方向性を持たない場合はゼロ。

以下のコードはストリームの向きを設定およびリセットします。

#include <cstdio>
#include <cstdlib>
#include <cwchar>
#include <iostream>
void show_orientation(int n)
{
    n < 0 ? std::wcout << "\tnarrow orientation\n" :
    n > 0 ? std::wcout << "\twide orientation\n" :
            std::wcout << "\tno orientation\n";
}
void try_read(FILE* fp)
{
    if (const int c = std::fgetc(fp); c == EOF)
        std::wcout << "\tnarrow character read failed\n";
    else
        std::wcout << "\tnarrow character read '" << static_cast<char>(c) << "'\n";
    if (const wint_t wc = std::fgetwc(fp); wc == WEOF)
        std::wcout << "\twide character read failed\n";
    else
        std::wcout << "\twide character read '" << static_cast<wchar_t>(wc) << "'\n";
}
int main()
{
    enum fwide_orientation : int { narrow = -1, query, wide };
    FILE* fp = std::fopen("main.cpp", "r");
    if (!fp)
    {
        std::wcerr << "fopen() failed\n";
        return EXIT_FAILURE;
    }
    std::wcout << "1) A newly opened stream has no orientation.\n";
    show_orientation(std::fwide(fp, fwide_orientation::query));
    std::wcout << "2) Establish byte orientation.\n";
    show_orientation(std::fwide(fp, fwide_orientation::narrow));
    try_read(fp);
    std::wcout << "3) Only freopen() can reset stream orientation.\n";
    if (std::freopen("main.cpp", "r", fp) == NULL)
    {
        std::wcerr << "freopen() failed\n";
        return EXIT_FAILURE;
    }
    std::wcout << "4) A reopened stream has no orientation.\n";
    show_orientation(std::fwide(fp, fwide_orientation::query));
    std::wcout << "5) Establish wide orientation.\n";
    show_orientation(std::fwide(fp, fwide_orientation::wide));
    try_read(fp);
    std::fclose(fp);
}

出力例:

1) A newly opened stream has no orientation.
        no orientation
2) Establish byte orientation.
        narrow orientation
        narrow character read '#'
        wide character read failed
3) Only freopen() can reset stream orientation.
4) A reopened stream has no orientation.
        no orientation
5) Establish wide orientation.
        wide orientation
        narrow character read failed
        wide character read '#'

関連項目

ファイルを開く
(関数)