Namespaces
Variants

std:: fgetws

From cppreference.net
< cpp ‎ | io ‎ | c
定义于头文件 <cwchar>
wchar_t * fgetws ( wchar_t * str, int count, std:: FILE * stream ) ;

从给定的文件流中读取最多 count - 1 个宽字符并存储到 str 中。生成的宽字符串始终以空字符结尾。若遇到文件结尾或换行宽字符则停止解析,此时 str 将包含该宽换行字符。

目录

参数

str - 用于读取字符的宽字符串
count - str 的长度
stream - 用于读取数据的文件流

返回值

str 成功时返回字符串指针,出错时返回空指针。

示例

#include <array>
#include <clocale>
#include <cstdio>
#include <cstdlib>
#include <cwchar>
#include <cwctype>
#include <iomanip>
#include <iostream>
#include <span>
#include <string>
void dump(std::span<const wchar_t> sp, std::size_t width = 14)
{
    for (wchar_t wc : sp)
        std::wcout << (std::iswprint(wc) ? wc : L'.');
    std::wcout << std::wstring(width > sp.size() ? width - sp.size() : 1, L' ')
               << std::hex << std::uppercase << std::setfill(L'0');
    for (wchar_t wc : sp)
        std::wcout << std::setw(sizeof wc) << static_cast<unsigned>(wc) << ' ';
    std::wcout << '\n';
}
int main()
{
    // 创建包含宽字符的临时文件
    std::setlocale(LC_ALL, "en_US.utf8");
    std::FILE* tmpf = std::tmpfile();
    for (const wchar_t* text : {
        L"Tétraèdre"    L"\n",
        L"Cube"         L"\n",
        L"Octaèdre"     L"\n",
        L"Icosaèdre"    L"\n",
        L"Dodécaèdre"   L"\n"
        })
        if (int rc = std::fputws(text, tmpf); rc == EOF)
        {
            std::perror("fputws()"); // POSIX 要求设置 errno
            return EXIT_FAILURE;
        }
    std::rewind(tmpf);
    std::array<wchar_t, 12> buf;
    while (std::fgetws(buf.data(), buf.size(), tmpf) != nullptr)
        dump(std::span(buf.data(), buf.size()));
    return EXIT_SUCCESS;
}

可能的输出:

Tétraèdre...  0054 00E9 0074 0072 0061 00E8 0064 0072 0065 000A 0000 0000 
Cube..dre...  0043 0075 0062 0065 000A 0000 0064 0072 0065 000A 0000 0000 
Octaèdre....  004F 0063 0074 0061 00E8 0064 0072 0065 000A 0000 0000 0000 
Icosaèdre...  0049 0063 006F 0073 0061 00E8 0064 0072 0065 000A 0000 0000 
Dodécaèdre..  0044 006F 0064 00E9 0063 0061 00E8 0064 0072 0065 000A 0000

参见

stdin 、文件流或缓冲区读取格式化宽字符输入
(函数)
从文件流获取宽字符
(函数)
将宽字符串写入文件流
(函数)
C 文档 关于 fgetws