Title here
Summary here
Here’s the translation of the Go code to C++, with explanations in Markdown format suitable for Hugo:
Writing files in C++ follows similar patterns to the ones we saw earlier for reading.
#include <iostream>
#include <fstream>
#include <vector>
#include <stdexcept>
void check(bool condition) {
if (!condition) {
throw std::runtime_error("An error occurred");
}
}
int main() {
// To start, here's how to dump a string (or just bytes) into a file.
std::string content = "hello\ncpp\n";
std::ofstream file1("/tmp/dat1");
check(file1.is_open());
file1 << content;
file1.close();
// For more granular writes, open a file for writing.
std::ofstream file2("/tmp/dat2");
check(file2.is_open());
// You can write byte vectors as you'd expect.
std::vector<char> d2 = {115, 111, 109, 101, 10};
file2.write(d2.data(), d2.size());
std::cout << "wrote " << d2.size() << " bytes\n";
// Writing strings is straightforward.
std::string s = "writes\n";
file2.write(s.c_str(), s.size());
std::cout << "wrote " << s.size() << " bytes\n";
// Flush writes to ensure they're written to stable storage.
file2.flush();
// C++ provides buffered writers through std::ofstream.
// The buffer is automatically managed.
file2 << "buffered\n";
std::cout << "wrote 9 bytes\n";
// The file is automatically closed when file2 goes out of scope.
// You can also explicitly close it:
file2.close();
return 0;
}
Try running the file-writing code.
$ g++ writing-files.cpp -o writing-files
$ ./writing-files
wrote 5 bytes
wrote 7 bytes
wrote 9 bytes
Then check the contents of the written files.
$ cat /tmp/dat1
hello
cpp
$ cat /tmp/dat2
some
writes
buffered
Next, we’ll look at applying some of the file I/O ideas we’ve just seen to the stdin
and stdout
streams.