Skip to content

Reading and Writing a file

Reading and Writing a File in C++

C++ provides a powerful set of file handling functions through the <fstream> header to:

  • Write data to a file using ofstream
  • Read data from a file using ifstream
  • Do both using fstream

πŸ”§ Step-by-Step Process

1. Include the Required Header

#include <fstream>

2. Create a File Stream Object

  • Use ofstream for writing
  • Use ifstream for reading
  • Use fstream for both

✍️ Writing to a File

βœ… Example: Writing Text to a File

#include <iostream>
#include <fstream>
using namespace std;

int main() {
ofstream outFile("myfile.txt"); // Open file in write mode

if (outFile.is_open()) {
outFile << "Hello BCA Students!\n";
outFile << "This is C++ file writing example.\n";
outFile.close(); // Close file
cout << "Data written successfully!" << endl;
} else {
cout << "Failed to open the file." << endl;
}

return 0;
}

πŸ”Ž What It Does:

  • Opens (or creates) myfile.txt
  • Writes two lines to the file
  • Closes the file

πŸ“– Reading from a File

βœ… Example: Reading Text from a File Line by Line

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
ifstream inFile("myfile.txt"); // Open file in read mode
string line;

if (inFile.is_open()) {
while (getline(inFile, line)) {
cout << line << endl;
}
inFile.close(); // Close file
} else {
cout << "Unable to open the file." << endl;
}

return 0;
}

πŸ”Ž What It Does:

  • Opens myfile.txt
  • Reads each line using getline()
  • Prints the content to the console

πŸ’‘ Reading and Writing Other Data Types

You can also read and write integers, floats, characters, etc.

βœ… Writing Numbers

ofstream file("numbers.txt");
int a = 100;
float b = 25.75;
file << a << " " << b;
file.close();

βœ… Reading Numbers

ifstream file("numbers.txt");
int x;
float y;
file >> x >> y;
cout << "x = " << x << ", y = " << y;
file.close();

πŸ“¦ Reading and Writing Using fstream (Both Read & Write)

#include <fstream>
using namespace std;

int main() {
fstream file;
file.open("data.txt", ios::out); // write mode
file << "BCA File Handling Example\n";
file.close();

file.open("data.txt", ios::in); // read mode
string line;
while (getline(file, line)) {
cout << line << endl;
}
file.close();

return 0;
}

πŸ“ Summary Table

OperationStream ClassFunction Used
Writing to fileofstream<<
Reading from fileifstream>> or getline()
Both read & writefstream<<, >>
Close a fileAny stream.close()

❗Best Practices

  • Always check if the file is open before reading or writing.
  • Always close the file after operations.
  • Handle possible file errors using is_open() or error messages.