命名空间
变体
操作

std::fwide

来自 cppreference.com
< 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