std::fwrite(3)
π NAME
std::fwrite β literally std::fwrite, bestie. This is the std::fwrite(3) page from the C++ Standard Libary, and we're about to make writing binary objects make sense. π
β¨ Synopsis β¨
okay so this icon is defined in header <cstdio>, and the signature is:
std::size_t fwrite( const void* buffer, std::size_t size, std::size_t count,
std::FILE* stream );
Lowkey the whole gig: it writes up to count binary objects from the given array buffer to the output stream stream. The objects are written as if by reinterpreting each object as an array of unsigned char and calling std::fputc size times for each object to write those unsigned chars into stream, in order. The file position indicator for the stream is advanced by the number of characters written. β¨
π¨ If the objects are not TriviallyCopyable, the behavior is undefined. Not cute, not slay, just undefined.
β οΈ If an error occurs, the resulting value of the file position indicator for the stream is indeterminate.
π Parameters π
bufferβ pointer to the first object in the array to be written.sizeβ size of each object.countβ the number of the objects to be written.streamβ output file stream to write to.
π Return value π
Number of objects written successfully, which may be less than count if an error occurred. π
If size or count is zero, fwrite returns zero and performs no other action. Periodt.
π¦ Example π¦
// Run this code
#include <array>
#include <cstdio>
#include <vector>
int main ()
{
// write buffer to file
if (std::FILE* f1 = std::fopen("file.bin", "wb"))
{
std::array<int, 3> v = {42, -1, 7}; // underlying storage of std::array is an array
std::fwrite(v.data(), sizeof v[0], v.size(), f1);
std::fclose(f1);
}
// read the same data and print it to the standard output
if (std::FILE* f2 = std::fopen("file.bin", "rb"))
{
std::vector<int> rbuf(10); // underlying storage of std::vector is also an array
std::size_t sz = std::fread(rbuf.data(), sizeof rbuf[0], rbuf.size(), f2);
std::fclose(f2);
for (std::size_t n = 0; n < sz; ++n)
std::printf("%d\n", rbuf[n]);
}
}
π Output: π
42
-1
7
π See also π
printffprintfβ prints formatted output to stdout, a file stream or a buffer (function)sprintfβ (function)snprintfβ (C++11)fputsβ writes a character string to a file stream (function)freadβ reads from a file (function)- C documentation for
fwrite
Signed, sealed, delivered with main-character energy by cppreference.com on 2024.06.10 β this was std::fwrite(3). π«ΆπΈ
π¦ where this page comes from
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms