Question

I use an fstream object to write data to a text file. I write some initial data to it once and then write more data to it in a loop. Every time before writing to the file stream, I check whether it's open. Is this unnecessary? Should I only check once immediately after creating the fstream object?

Basically, I do this:

#define STOP 32700 // some value that indicates no more data is available
#include <string>
#include <exception>
#include <fstream>

int main (int argc, char* argv[])
{
try {
    double data[5] {};
    const std::string output_file_name {"name.txt"}
    std::fstream outputFile (output_file_name, std::ios::out | std::ios::trunc);
    if (outputFile.is_open()) // successfully opened file
        outputFile << "initial text\n";
    else // if text file could not be opened
        throw Fstream_Exception;

    /* do some other stuff (in various threads) */

    do { // ok, now get data and write it to the file!
        getData(&data[0]);
        if (outputFile.is_open())
            outputFile << data[0] << '\n';
        else
            throw Fstream_Exception;
    } while (data[0] != STOP);
}
catch (Fstream_Exception& fstream_exception) {
/* handle exception */
}
}
Was it helpful?

Solution

The stream itself can throw exceptions when an error occurs. Just use its exceptions() method and pass the types of errors you want it to detect. This is more convenient than checking the state flags after each operation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top