如何在 Win32 上的缓冲区中读取整个文件wchar_t

How do I read the whole file in wchar_t buffer on Win32?

本文关键字:文件 wchar 读取 Win32 缓冲区      更新时间:2023-10-16

我在将 UTF8 编码的文件读取到wchar_t缓冲区时遇到问题,因为我事先不知道文件大小。

有谁知道我如何在缓冲区中读取整个文件?

我想我必须保留一个wchar_t *(指针)并在阅读时调整它的大小。然而,这听起来很可怕,因为我以前从未调整过指针的大小。

我正在使用Microsoft Visual Studio进行Windows C++编程。

您是否考虑过使用向量?

#include <vector>
#include <fstream>
#include <iterator>
:::
std::wifstream in(file_name);
//Will automatically reallocate to the require size
std::vector<wchar_t> store {
    std::istream_iterator<wchar_t, wchar_t>(in),
    std::istream_iterator<wchar_t, wchar_t>()};
//to access wchar_t* you can call data();
my_func(store.data());
如果要

分配文件大小的缓冲区,则首先需要查找文件大小。 为此,您可以使用适当的参数调用 stat() 函数,它会填充包含文件大小的字段。

假设您将该大小存储在变量 filesize 中。

然后你可以

wchar_t *buffer = reinterpret_cast< wchar_t * >new char [ filesize ];
然后在调用 open() 获取文件描述符后,使用 read() 将整个文件

读入该缓冲区,或者在调用 fopen() 获取文件 * 后使用 fread() 读取整个文件。