15.4. File output¶
std::ofstream writes to a file. Opening an output file normally truncates
its old contents; use a different output name when copying a file. If you
intend to append instead, open it with std::ios::app. Both file stream
types are declared in <fstream>.
The following program copies whole lines. It checks input and output opening separately so its error messages identify the failed operation. It also checks writes and the explicit close: an output failure may be reported only when buffered output is flushed.
1#include <fstream>
2#include <iostream>
3#include <string>
4
5int main() {
6 std::ifstream input("c192_readings.txt");
7 if (!input) {
8 std::cerr << "Unable to open input\n";
9 return 1;
10 }
11 std::ofstream output("readings_copy.txt");
12 if (!output) {
13 std::cerr << "Unable to open output\n";
14 return 1;
15 }
16 std::string line;
17 while (std::getline(input, line)) {
18 output << line << '\n';
19 if (!output) {
20 std::cerr << "Write failed\n";
21 return 1;
22 }
23 }
24 if (input.bad() || !input.eof()) {
25 std::cerr << "Read failed\n";
26 return 1;
27 }
28 output.close();
29 if (!output) {
30 std::cerr << "Unable to finish output\n";
31 return 1;
32 }
33 std::cout << "Copy complete\n";
34}
This copies text lines, adding a newline after each one. It is not a byte-for-byte copy when the original file has no final newline. If exact bytes matter, that is a different requirement.
Write the values in readings to readings.txt, one per line.
Return a nonzero status from main if opening or writing fails.
Assume the headers and readings are supplied.
-
output << reading << '\n'; } -
for (int reading : readings) { -
if (!output) { return 1; } -
if (!output) { return 1; } -
output.close(); -
std::ofstream output("readings.txt");
The code from the previous problem checks whether the files open or not. It doesn't specify which one, if any, doesn't open. How could you specify which file does not open?
Complete the type: output("results.txt");.