Writing Files in Cilk

Here’s the translation of the Go code to Cilk, formatted in Markdown suitable for Hugo:

Writing files in Cilk follows similar patterns to the ones we saw earlier for reading.

#include <cilk/cilk.h>
#include <iostream>
#include <fstream>
#include <vector>
#include <cstdlib>

void check(bool condition) {
    if (!condition) {
        std::cerr << "Error occurred" << std::endl;
        exit(1);
    }
}

int main() {
    // To start, here's how to dump a string (or just bytes) into a file.
    std::string content = "hello\ncilk\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());

    // It's idiomatic to close the file immediately after opening it.
    // In C++, we can use RAII to automatically close the file when it goes out of scope.

    // You can write byte vectors as you'd expect.
    std::vector<char> d2 = {'s', 'o', 'm', 'e', '\n'};
    file2.write(d2.data(), d2.size());
    std::cout << "wrote " << d2.size() << " bytes\n";

    // Writing strings is also available.
    std::string s = "writes\n";
    file2 << s;
    std::cout << "wrote " << s.length() << " bytes\n";

    // In C++, writes are typically buffered and flushed automatically,
    // but you can force a flush if needed.
    file2.flush();

    // C++ streams provide buffered writers by default.
    file2 << "buffered\n";
    std::cout << "wrote " << strlen("buffered\n") << " bytes\n";

    // The file will be automatically closed when file2 goes out of scope.
    return 0;
}

Try running the file-writing code.

$ g++ -fcilkplus 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
cilk
$ 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.