Welcome to the exciting world of C++ File I/O! In this lesson, we'll dive into the art of reading and writing data files in C++, making your programs more powerful and versatile. Let's get started!
File I/O stands for Input/Output, which is the process of reading data from a file (Input) and writing data to a file (Output). This allows us to store and retrieve data even when the program is not running, making it an essential tool for creating robust applications.
In C++, File I/O is handled through streams. A stream is an abstract sequence of bytes that can be read from or written to. The standard C++ library provides three types of streams:
std::ifstream - for reading files (Input File Stream)std::ofstream - for writing files (Output File Stream)std::fstream - for both reading and writing files (File Stream)To work with files, we first need to open them using the open() function and then close them using the close() function. Here's an example of opening a file for writing:
#include <fstream>
std::ofstream file("example.txt");
// Now we can write to "example.txt"
file << "Hello, World!";
// Don't forget to close the file when you're done!
file.close();š Note: Always remember to close the file when you're finished, as this ensures that all data is written properly and resources are freed up.
Reading from a file is similar to writing, but we use an std::ifstream instead of an std::ofstream. Here's an example of reading data from a file:
#include <fstream>
#include <string>
std::ifstream file("example.txt");
std::string content;
// Read the entire file into a string
file >> content;
// Print the contents
std::cout << content;
// Don't forget to close the file when you're done!
file.close();Writing to a file is straightforward using an std::ofstream. Here's an example of writing data to a file:
#include <fstream>
std::ofstream file("example.txt");
// Write some data to the file
file << "Hello, World!";
file << "This is an example.";
// Don't forget to close the file when you're done!
file.close();Let's create a simple program that reads data from a file and writes it to another file.
#include <fstream>
#include <string>
int main() {
std::ifstream inputFile("input.txt");
std::ofstream outputFile("output.txt");
std::string line;
// Read lines from input.txt and write them to output.txt
while (std::getline(inputFile, line)) {
outputFile << line << '\n';
}
// Don't forget to close the files when you're done!
inputFile.close();
outputFile.close();
return 0;
}Which stream is used for reading files in C++?
That's it for this lesson! With these concepts, you're now ready to dive deeper into C++ File I/O and create more powerful and versatile programs. Stay tuned for more exciting lessons on C++! šš»