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; ...