Writing bytes

In addition to writing by field, writing a stream of bytes is also supported. In the following example, we write a single byte to the file (in addition to a newline) using the put() function, which is similar to get() but used for writing instead of reading:

#include <fstream>#include <iostream>int main(){    if (auto file = std::fstream("test.txt")) {        file.put('H');        file.put('\n');    }}// > g++ -std=c++17 scratchpad.cpp; echo "" > test.txt; ./a.out; cat test.txt// H

Multiple bytes can also be written using the write() function, as follows:

#include <fstream>#include <iostream>int main(){    if (auto file = std::fstream("test.txt")) {        file.write("Hello World\n", 12);    }}// > g++ -std=c++17 scratchpad.cpp; echo "" > test.txt; ./a.out; ...

Get Hands-On System Programming with C++ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.