File Handling
File Handling
Creating files
Writing data into files
Reading data from files
In C++, we use:
e
ifstream – to read from a file ("input from computer to the monitor //input
filestream")
w
fstream – to read and write both
im
ios::in : open for input (reading)
ios::binary : open file in binary mode e.g pictures ,videos and music
ar
#include <fstream>
Writing to a File
K
#include <iostream>
#include <fstream> //Required for file handling
using namespace std;
int main() {
ofstream outFile("example.txt"); //Create or open file for writing
if (outFile.is_open()) {
File Handling Compiled by chara1 Petros Psuedo
e
}
w
It creates a file called exanple.txt
It writes two lines of text into the file
im
You can open example.txt later and see the text inside
#include <fstream>
ar
#include <string>
using namespace std;
h
int main() {
.C
string line;
if (inFile.is_open()) {
P.
return 0;
}
It opens example.txt
It reads each line one by one
It shows the lines on the screen
We want to add more text to a file without deleting what's already there.
#include <iostream>
e
#include <fstream>
w
using namespace std;
im
int main() {
ofstream outFile("example.txt", ios::app); // Open in append mode
h
if (outFile.is_open()) {
ac
outFile << "Appended line!" << endl;
outFile.close();// Close the file
ar
} else {
cout << "Unable to open file.";
h
}
return 0;
.C
}
K
if (file.is_open()) {
// Read first
string line;
while (getline(file, line)) {
cout << line << endl;
}
// Move to end to write
e
file.clear(); // Clear EOF flag
w
file.seekp(0, ios::end); // Move write pointer to end
file << "New data with fstream!" << endl;
im
file.close();
} else {
h
cout << "Unable to open file.";
ac
}
return 0;
}
ar
It opens myfile.txt
It reads each line one by one
h
If a file doesn't exist, C++ can create it for you when writing
Use "filename.txt" to create or open text files
P.
#include <iostream>
#include <fstream>
using namespace std;
File Handling Compiled by chara1 Petros Psuedo
int main() {
string name;
//Ask user for their name
cout << "Enter your name: ";
getline(cin, name);
e
string savedName;
w
ifstream fileIn("user.txt"); // Open file to read
getline(fileIn, savedName);
fileIn.close(); // Close file after reading
im
// Step 3: Show name
cout << "Name read from file: " << savedName << endl;
h
return 0;
}
ac
1. Add tasks
2. View saved tasks
P.
#include <iostream>
#include <fstream>
int main() {
int choice;
string task;
File Handling Compiled by chara1 Petros Psuedo
if (choice == 1) {
// Add task
e
w
cout << "Enter your task: ";
getline(cin, task);
im
ofstream file("tasks.txt", ios::app); // Open in append mode
} else if (choice == 2) {
ar
// View tasks
h
ifstream file("tasks.txt");
file.close();
} else {
}
File Handling Compiled by chara1 Petros Psuedo
return 0;
how to write a C++ file handling program for counting, there are several ways
to understand this depending on what you want to count:
e
1. Count how many lines are in a file?
w
2. Count how many words are in a file?
3. Count how many characters are in a file?
4. Count how many times a certain word appears in the file?
im
Let me give you simple examples for each.
We want to:
h
1. Read a text file
ac
2. Count:
o ʮ Number of lines
o ˀ Number of words
o ̍ Number of characters
ar
Ӈ What is a line?
.C
Hello world
K
#include <iostream>
#include <fstream>
#include <string>
int main() {
string line;
int count = 0;
e
w
file.close();
im
return 0;
}
h
ͧ Explanation
ac
Code:
.C
#include <iostream>
#include <fstream>
K
#include <string>
P.
int main() {
ifstream file("sample.txt");
string word;
int count = 0;
File Handling Compiled by chara1 Petros Psuedo
count++;
file.close();
return 0;
e
w
ͧ How it works:
file >> word reads one word at a time (words are split by space)
im
count++ adds to the count for each word
#include <iostream>
h
#include <fstream>
ac
int main() {
ifstream file("sample.txt");
h
char ch;
.C
int count = 0;
while (file.get(ch)) {
K
count++;
P.
file.close();
return 0;
}
File Handling Compiled by chara1 Petros Psuedo
ͧ How it works:
#include <iostream>
#include <fstream>
#include <string>
e
using namespace std;
w
int main() {
im
ifstream file("sample.txt");
string word;
int count = 0;
h
string target = "apple"; // the word to search
ac
if (word == target) {
count++;
h
}
.C
file.close();
K
cout << "The word '" << target << "' appears " << count << " times." << endl;
P.
return 0;
If you want the user to enter text, and then save that text into a file, and later count
lines, words, or characters, here's how you do it step by step.
Goal:
e
ˇ Code:
w
#include <iostream>
#include <fstream>
im
#include <string>
string line;
ar
while (true) {
.C
getline(cin, line);
file.close();
return 0;
Explanation:
File Handling Compiled by chara1 Petros Psuedo
Count lines
Count words
Count characters
e
You can use this menu-based code to let the user choose what to count.
w
Ӈ Full Program: Save Text + Count It
im
#include <iostream>
#include <fstream>
h
#include <string>
ac
using namespace std;
void getUserInput() {
ar
ofstream file("input.txt");
string line;
h
while (true) {
K
getline(cin, line);
file.close();
void countLines() {
File Handling Compiled by chara1 Petros Psuedo
ifstream file("input.txt");
string line;
int count = 0;
count++;
file.close();
e
w
cout << "Total lines: " << count << endl;
im
void countWords() {
ifstream file("input.txt");
h
string word;
ac
int count = 0;
count++;
h
file.close();
.C
}
P.
void countCharacters() {
ifstream file("input.txt");
char ch;
int count = 0;
while (file.get(ch)) {
File Handling Compiled by chara1 Petros Psuedo
count++;
file.close();
int main() {
int choice;
e
w
cout << "1. Enter Text\n2. Count Lines\n3. Count Words\n4. Count
Characters\nEnter your choice: ";
im
cin >> choice;
return 0;
K
}
P.
How it Works
ӑ Try It!
File Handling Compiled by chara1 Petros Psuedo
Try entering:
Hello there
I love coding
END
e
What Is a Blank Space?
w
A blank space is simply the ' ' character (space bar).
Example text:
im
Hello world I love C++
ȴ It has 4 spaces.
h
Ӈ Idea:
ac
We’ll open the file, read it character by character, and count how many times we see
a space (' ').
ar
#include <iostream>
h
#include <fstream>
.C
int main() {
K
char ch;
int spaceCount = 0;
if (!file) {
return 1;
}
File Handling Compiled by chara1 Petros Psuedo
while (file.get(ch)) {
spaceCount++;
file.close();
cout << "Number of blank spaces: " << spaceCount << endl;
e
w
return 0;
im
ͧ Explanation:
void countSpaces() {
ifstream file("input.txt");
.C
char ch;
K
int count = 0;
P.
while (file.get(ch)) {
file.close();
}
File Handling Compiled by chara1 Petros Psuedo
And in main():
Then add:
case 5: countSpaces(); break;
Final Tips
e
why we use return 1; in this line:
w
if (!file) {
im
cout << "File could not be opened.\n";
return 1; // <---- Why this?
}
h
Short Answer:
ac
return 1; means the program is exiting early because something went wrong — in this
case, the file didn’t open. The number 1 is a signal that an error happened.
ar
./my_program
File Handling Compiled by chara1 Petros Psuedo
If the file fails to open and you return 1, the terminal knows:
"Something went wrong."
echo $?
e
Use return 1; when :
w
A file can’t be opened
A value is invalid
Something serious stops the program from continuing
im
Summary
return 0; → success
h
return 1; → something went wrong
It’s a way to communicate errors clearly
ac
ar
h
.C
K
P.