<ofstream>
The <ofstream>
header is part of the C++ Standard Library's I/O stream classes. It provides the std::ofstream
class, which is used for writing to files. This class inherits from std::ostream
and adds file-specific functionality for output operations.
std::ofstream
: The main class for file output operations#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ofstream outFile("example.txt");
if (outFile.is_open()) {
outFile << "Writing to a file using ofstream." << std::endl;
outFile << "This is another line." << std::endl;
outFile.close();
std::cout << "Successfully wrote to the file." << std::endl;
} else {
std::cerr << "Unable to open file" << std::endl;
}
return 0;
}
<<
operator#include <iostream>
#include <fstream>
int main() {
std::ofstream outFile("log.txt", std::ios::app);
if (outFile.is_open()) {
outFile << "Appending this line to the file." << std::endl;
outFile.close();
std::cout << "Successfully appended to the file." << std::endl;
} else {
std::cerr << "Unable to open file" << std::endl;
}
return 0;
}
std::ios::app
#include <iostream>
#include <fstream>
#include <vector>
struct Record {
int id;
char name[20];
double score;
};
int main() {
std::vector<Record> records = {
{1, "Alice", 95.5},
{2, "Bob", 87.3},
{3, "Charlie", 91.8}
};
std::ofstream outFile("records.bin", std::ios::binary);
if (outFile.is_open()) {
for (const auto& record : records) {
outFile.write(reinterpret_cast<const char*>(&record), sizeof(Record));
}
outFile.close();
std::cout << "Successfully wrote binary data to the file." << std::endl;
} else {
std::cerr << "Unable to open file" << std::endl;
}
return 0;
}
std::ios::binary
write()
std::fstream
for both reading and writing to the same fileThe <ofstream>
header and std::ofstream
class provide a convenient and type-safe way to write data to files in C++.
std::ofstream
for file output operationsBy using <ofstream>
, C++ developers can easily implement file writing operations, whether for simple text files or more complex binary data structures. It provides a flexible and object-oriented approach to file I/O, consistent with C++'s stream-based input/output philosophy.
[1] https://cplusplus.com/reference/fstream/ofstream/ [2] https://learn.microsoft.com/en-us/cpp/standard-library/basic-ofstream-class?view=msvc-170 [3] https://stackoverflow.com/questions/11060874/usage-of-ofstream [4] https://stackoverflow.com/questions/72999240/initializing-stdofstream-object-in-header-file-v-s-source-file [5] https://cplusplus.com/reference/fstream/ofstream/ofstream/ [6] https://stackoverflow.com/questions/71336125/best-practice-when-dealing-with-c-iostreams [7] https://www.machinet.net/tutorial-eng/optimizing-file-output-operations-using-std-ofstream-in-cpp [8] https://www.machinet.net/tutorial-eng/common-pitfalls-with-cpp-fstream-and-how-to-avoid-them
Previous Page | Course Schedule | Course Content