命名空间
变体
操作

std::fwide

来自 cppreference.cn
< 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 - 整数值,大于零以设置流为宽定向,小于零以设置流为窄定向,或零以只查询

[编辑] 返回值

若此调用后流为宽定向则返回大于零的整数,若此调用后流为字节定向则返回小于零的整数,若流无定向则返回零。

[编辑] 示例

以下代码设置并重置流的定向。

#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 '#'

[编辑] 参阅

打开文件
(函数) [编辑]
C 文档 关于 fwide