#includeint main() { std::ofstream file("example.txt"); if (!file.is_open()) { return 1; } // Write some data to the file file << "Hello world!"; // Check for an error if (file.fail()) { std::cerr << "Error writing to file." << std::endl; } // Clear any error flags file.clear(); // Write some more data to the file file << "This is a new line."; return 0; }
#includeIn this example, we create a new file stream object with `std::ofstream` and write some data to it. We then use `clear()` to clear any error flags, but instead of writing more data, we pass `std::ofstream::goodbit` as an argument to clear only the `eofbit` and `failbit` flags. Finally, we attempt to write to the file again, which will overwrite the previous data. Package/library: This code uses the `fstream` library, which is part of the C++ standard library.int main() { std::ofstream file("example.txt"); if (!file.is_open()) { return 1; } // Write some data to the file file << "Hello world!"; // Clear the error flags without writing more data file.clear(std::ofstream::goodbit); // Attempt to write to the file again file << "This will overwrite the previous data."; return 0; }