C ++ offers different data read / write abstractions, in general these abstractions are separated into buffers (buffer) and flows ( stream ).
There are conceptual nuances between a buffer and a flow, in general:
- Buffers are usually an intermediate and temporary step in further processing.
- Flows are usually a direct and continuous input of data.
Based on these different concepts, the class basic_filebuf
offers utilities to manage the buffer (advance, rewind, synchronize ...).
What is the basic_filebuf
for?
To begin with, you are not expected to use std::basic_filebuf
directly if not any of your aliases: filebuf
with char
as underlying type or wfilebuf
with wchar_t
as underlying type.
Its usefulness is to treat files (file) as data buffers, and therefore it offers raw data reading and writing tools but it lacks reading and writing tools with formatted data, for this kind of utility you were probably looking for std::basic_fstream
that if offers the data insertion operator ( operator <<
) of which std::basic_filebuf
lacks.
Can you give me an example in code that uses filebuf
?
In the Microsoft documentation about basic_filebuf
you have a Hex Dump implemented with that class. But if you think a very complicated example, I leave an example of reading and writing:
template <typename T>
void escribir(T valor)
{
std::cout << "Escribir " << valor << '\n';
std::filebuf archivo;
if (archivo.open("archivo.bin", std::ios_base::out | std::ios_base::binary))
{
archivo.sputn(reinterpret_cast<const char *>(&valor), sizeof(valor));
}
}
template <typename T>
void leer(T &valor)
{
std::cout << "Leer sobre " << &valor;
std::filebuf archivo;
if (archivo.open("archivo.bin", std::ios_base::in | std::ios_base::binary))
{
archivo.sgetn(reinterpret_cast<char *>(&valor), sizeof(valor));
}
std::cout << " leido " << valor << '\n';
}
You can see the code working in Wandbox 三 へ (へ ਊ) へ ハ ッ ハ ッ .