Reputation: 79539
I'm having trouble reading a file in UTF8 encoding into a wchar_t
buffer as I don't know the file size in advance.
Does anyone know how I can read the whole file in a buffer?
I imagine I'd have to keep a wchar_t *
(pointer) and resize it as I read. However that sounds very scary as I haven't ever resized pointers before.
I'm doing Windows C++ programming with Microsoft Visual Studio.
Upvotes: 1
Views: 3090
Reputation: 16168
Have you considered using a vector?
#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());
Upvotes: 2
Reputation: 2491
If you want to allocate a buffer the size of the file you first need to find the file size. To do that, you call the stat() function, with appropriate arguments, and it fills in a field containing the file size.
Suppose you store that size in the variable filesize
.
Then you can
wchar_t *buffer = reinterpret_cast< wchar_t * >new char [ filesize ];
and then read the whole file into that buffer, using read(), after having called open() on it to get a file descriptor, or fread() after having called fopen() to get a FILE *.
Upvotes: -1