GCC Code Coverage Report


Directory: gridformat/
File: gridformat/common/output_file.hpp
Date: 2026-10-12 17:50:57
Exec Total Coverage
Lines: 9 9 100.0%
Functions: 147 147 100.0%
Branches: 15 24 62.5%

Line Branch Exec Source
1 // SPDX-FileCopyrightText: 2026 Dennis Gläser <dennis.a.glaeser@gmail.com>
2 // SPDX-License-Identifier: MIT
3 /*!
4 * \file
5 * \ingroup Common
6 * \brief Helper for writing into files with error checking.
7 */
8 #ifndef GRIDFORMAT_COMMON_OUTPUT_FILE_HPP_
9 #define GRIDFORMAT_COMMON_OUTPUT_FILE_HPP_
10
11 #include <string>
12 #include <ostream>
13 #include <fstream>
14 #include <concepts>
15
16 #include <gridformat/common/exceptions.hpp>
17
18 namespace GridFormat {
19
20 /*!
21 * \ingroup Common
22 * \brief Open the file with the given name, pass it to the given callback and close it.
23 * Throws an IOError if the file cannot be opened or if writing to it fails.
24 */
25 template<std::invocable<std::ostream&> C>
26 21196 void write_to(const std::string& filename, C&& callback) {
27
1/2
✓ Branch 1 taken 10617 times.
✗ Branch 2 not taken.
21196 std::ofstream file{filename, std::ios::out};
28
2/2
✓ Branch 1 taken 19 times.
✓ Branch 2 taken 10598 times.
21196 if (!file.is_open())
29
3/6
✓ Branch 2 taken 19 times.
✗ Branch 3 not taken.
✓ Branch 5 taken 19 times.
✗ Branch 6 not taken.
✓ Branch 9 taken 19 times.
✗ Branch 10 not taken.
38 throw IOError("Could not open file '" + filename + "' for writing");
30
2/2
✓ Branch 1 taken 10004 times.
✓ Branch 2 taken 594 times.
21158 callback(file);
31
1/2
✓ Branch 1 taken 10004 times.
✗ Branch 2 not taken.
19970 file.close();
32
3/4
✓ Branch 1 taken 10004 times.
✗ Branch 2 not taken.
✓ Branch 3 taken 1 times.
✓ Branch 4 taken 10003 times.
19970 if (file.fail())
33
3/6
✓ Branch 2 taken 1 times.
✗ Branch 3 not taken.
✓ Branch 5 taken 1 times.
✗ Branch 6 not taken.
✓ Branch 9 taken 1 times.
✗ Branch 10 not taken.
2 throw IOError("Error while writing file '" + filename + "'");
34 21196 }
35
36 } // namespace GridFormat
37
38 #endif // GRIDFORMAT_COMMON_OUTPUT_FILE_HPP_
39