Namespaces
Variants

fwide

From cppreference.net
< c ‎ | io
定义于头文件 <wchar.h>
int fwide ( FILE * stream, int mode ) ;
(C95 起)

如果 mode > 0 ,尝试使 stream 成为宽面向。如果 mode < 0 ,尝试使 stream 成为字节面向。如果 mode == 0 ,仅查询流的当前面向。

如果流的定向已经确定(通过执行输出操作或先前调用 fwide ),此函数不执行任何操作。

目录

参数

stream - 指向待修改或查询的C I/O流的指针
mode - 整数值:大于零时设置流为宽模式,小于零时设置流为窄模式,等于零时仅进行查询

返回值

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

示例

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

#include <stdio.h>
#include <stdlib.h>
#include <wchar.h>
void show_orientation(int n)
{
    n < 0 ? puts("\tnarrow orientation"):
    n > 0 ? puts("\twide orientation"):
            puts("\tno orientation");
}
void try_read(FILE* fp)
{
    int c = fgetc(fp);
    c == EOF
        ? printf("\tnarrow character read failed\n")
        : printf("\tnarrow character read '%c'\n", c);
    wint_t wc = fgetwc(fp);
    wc == WEOF
        ? printf("\twide character read failed\n")
        : printf("\twide character read '%lc'\n", wc);
}
int main(void)
{
    enum fwide_orientation { narrow = -1, query, wide };
    FILE* fp = fopen("main.cpp", "r");
    if (!fp)
    {
        perror("fopen() failed");
        return EXIT_FAILURE;
    }
    puts("1) A newly opened stream has no orientation.");
    show_orientation(fwide(fp, query));
    puts("2) Establish byte orientation.");
    show_orientation(fwide(fp, narrow));
    try_read(fp);
    puts("3) Only freopen() can reset stream orientation.");
    if (freopen("main.cpp", "r", fp) == NULL)
    {
       perror("freopen() failed");
       return EXIT_FAILURE;
    }
    puts("4) A reopened stream has no orientation.");
    show_orientation(fwide(fp, query));
    puts("5) Establish wide orientation.");
    show_orientation(fwide(fp, wide));
    try_read(fp);
    fclose(fp);
}

可能的输出:

1) 新打开的流无定向。
        无定向
2) 建立字节定向。
        窄定向
        窄字符读取 '#'
        宽字符读取失败
3) 只有 freopen() 可以重置流定向。
4) 重新打开的流无定向。
        无定向
5) 建立宽定向。
        宽定向
        窄字符读取失败
        宽字符读取 '#'

参考文献

  • C23 标准 (ISO/IEC 9899:2024):
  • 7.29.3.5 fwide 函数 (页: TBD)
  • C17 标准 (ISO/IEC 9899:2018):
  • 7.29.3.5 fwide 函数 (页: 309)
  • C11 标准 (ISO/IEC 9899:2011):
  • 7.29.3.5 fwide 函数 (p: 423)
  • C99标准(ISO/IEC 9899:1999):
  • 7.24.3.5 fwide函数(页码:369)

参见

打开文件
(函数)
C++ 文档 for fwide