This tutorial aims to introduce you to the basics of file handling in C++. File handling is an essential part of programming that deals with creating, reading, writing, and closing files.
By the end of this tutorial, you will learn how to:
- Open a file
- Read from a file
- Write to a file
- Close a file
Prerequisites: A basic understanding of C++ programming language.
In C++, we use the fstream
library to work with files. The fstream
library provides the fstream
class to read and write to files.
To open a file, we use open
function of fstream
or ofstream
or ifstream
objects.
fstream myFile;
myFile.open("example.txt");
To read from a file, we use the >>
operator.
string lineData;
myFile >> lineData;
To write to a file, we use the <<
operator.
myFile << "This is a new line of text";
After we are done with our operations on the file, we close the file by calling the close
method of the fstream
object.
myFile.close();
#include <fstream>
int main() {
std::ofstream myFile;
myFile.open("example.txt");
if (myFile.is_open()) {
myFile << "This is a new line of text\n";
}
myFile.close();
return 0;
}
This C++ code opens a file named "example.txt", writes a line of text to it, and then closes the file.
#include <fstream>
#include <string>
#include <iostream>
int main() {
std::ifstream myFile;
myFile.open("example.txt");
if (myFile.is_open()) {
std::string lineData;
while (getline(myFile, lineData)) {
std::cout << lineData << "\n";
}
}
myFile.close();
return 0;
}
This C++ code opens a file named "example.txt", reads line by line from it, prints each line to the console, and then closes the file.
In this tutorial, you learned the basics of file handling in C++. You learned how to open, read from, write to, and close files using the fstream
library in C++.
For further learning, you can explore how to handle errors during file operations and how to work with binary files.
Here are the solutions for the above exercises:
#include <fstream>
int main() {
std::ofstream myFile;
myFile.open("numbers.txt");
if (myFile.is_open()) {
for (int i = 1; i <= 10; i++) {
myFile << i << "\n";
}
}
myFile.close();
return 0;
}
#include <fstream>
#include <string>
#include <iostream>
int main() {
std::ifstream myFile;
myFile.open("numbers.txt");
if (myFile.is_open()) {
std::string lineData;
while (getline(myFile, lineData)) {
std::cout << lineData << "\n";
}
}
myFile.close();
return 0;
}
#include <fstream>
#include <string>
#include <iostream>
int main() {
std::ofstream myFile;
myFile.open("repeatedString.txt");
if (myFile.is_open()) {
std::string myString;
int n;
std::cout << "Enter a string: ";
getline(std::cin, myString);
std::cout << "Enter a number: ";
std::cin >> n;
for (int i = 0; i < n; i++) {
myFile << myString << "\n";
}
}
myFile.close();
return 0;
}