0% found this document useful (0 votes)
2 views18 pages

File Handling

The document provides a comprehensive guide on file handling in C++, covering file creation, reading, writing, and appending using the <fstream> library. It includes code examples for various operations such as saving user input to a file, reading from a file, and counting lines, words, and characters in a file. Additionally, it suggests a mini project idea for a To-Do List app and offers tips for beginners.

Uploaded by

tbchaps2604
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views18 pages

File Handling

The document provides a comprehensive guide on file handling in C++, covering file creation, reading, writing, and appending using the <fstream> library. It includes code examples for various operations such as saving user input to a file, reading from a file, and counting lines, words, and characters in a file. Additionally, it suggests a mini project idea for a To-Do List app and offers tips for beginners.

Uploaded by

tbchaps2604
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

File Handling Compiled by chara1 Petros Psuedo

File handling in C++ means:

 Creating files
 Writing data into files
 Reading data from files

classes for file handling are from the <fstream> library:

In C++, we use:

 ofstream – to write to a file ("output from user to the computer //output


filestream")

e
 ifstream – to read from a file ("input from computer to the monitor //input
filestream")

w
 fstream – to read and write both

modes to control file operations

im
ios::in : open for input (reading)

ios::out : open for output (writing)


h
ios::app : append to existing file
ac

ios::trunc : truncate existing file

ios::binary : open file in binary mode e.g pictures ,videos and music
ar

NB: All of these come from the <fstream> library.


h

1. Include the Required Header


.C

#include <fstream>
Writing to a File
K

We want to create a file and put some text inside.


P.

#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

outFile << "Hello, file!" << endl;


outFile << "This is a test." << endl;
outFile.close(); // Close the file when done
}
else {
cout << "Unable to open file for writing.";
}
return 0;

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

2. Reading from a File (See what's inside)


h
We want to open a file and read the text inside.
ac
#include <iostream>

#include <fstream>
ar

#include <string>
using namespace std;
h

int main() {
.C

ifstream inFile("example.txt"); // Open the file


K

string line;
if (inFile.is_open()) {
P.

while (getline(inFile, line)) {


cout << line << endl; // Output the text line by line
}
inFile.close(); // Close the file
} else {
cout << "Unable to open file for reading.";
}
File Handling Compiled by chara1 Petros Psuedo

return 0;
}

 It opens example.txt
 It reads each line one by one
 It shows the lines on the screen

3. Appending to a File (Add more text)

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

 It opens example.txt in append mode


 It adds a new line at the end of the file
P.

Using fstream for Both Reading and Writing


#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
fstream file("example.txt", ios::in | ios::out);
File Handling Compiled by chara1 Petros Psuedo

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

 It shows the lines on the screen


.C

Tips for Beginners

 Always close() the file when you're done


K

 If a file doesn't exist, C++ can create it for you when writing
 Use "filename.txt" to create or open text files
P.

Practice Exercise: Save and Read a Name

1. Ask the user for their name


2. Save it in a file
3. Read it back from the file and show it on the screen

#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);

// Step 1: Write name to file


ofstream fileOut("user.txt"); // Create or open file to write
fileOut << name;
fileOut.close(); // Close file after writing

// Step 2: Read name from file

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

What You Learn:


ar

 How to get input from user


 How to save it to a file
 How to read it back
h

Mini Project Idea: To-Do List App (Simple)


.C

Let’s make a simple program where the user can:


K

1. Add tasks
2. View saved tasks
P.

#include <iostream>

#include <fstream>

using namespace std;

int main() {

int choice;

string task;
File Handling Compiled by chara1 Petros Psuedo

cout << "1. Add Task\n";

cout << "2. View Tasks\n";

cout << "Enter your choice: ";

cin >> choice;

cin.ignore(); // Clear input buffer

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

file << task << endl;


h
file.close();
ac

cout << "Task saved!\n";

} else if (choice == 2) {
ar

// View tasks
h

ifstream file("tasks.txt");

cout << "Your Tasks:\n";


.C

while (getline(file, task)) {


K

cout << "- " << task << endl;


P.

file.close();

} else {

cout << "Invalid choice.\n";

}
File Handling Compiled by chara1 Petros Psuedo

return 0;

 Run the code once, choose 1 and add a task.


 Run again, choose 2 to view your saved tasks.
 Try adding more tasks to see them all saved!

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

o ˪ How many times a specific word appears

Step-by-Step: Count Lines in a File


h

Ӈ What is a line?
.C

A line is one row of text. This file has 3 lines:

Hello world
K

How are you?


P.

I'm learning C++

Ž Code to Count Lines

#include <iostream>

#include <fstream>

#include <string>

using namespace std;


File Handling Compiled by chara1 Petros Psuedo

int main() {

ifstream file("sample.txt"); // Open the file

string line;

int count = 0;

while (getline(file, line)) {

count++; // Count each line

e
w
file.close();

cout << "Number of lines: " << count << endl;

im
return 0;

}
h
ͧ Explanation
ac

 ifstream file("sample.txt");: Opens file for reading


 getline(file, line): Reads one full line into a string
 count++: Adds 1 to the counter each time a line is read
ar

 file.close();: Always close the file

ӕ Count Words in a File


h

Ž Code:
.C

#include <iostream>

#include <fstream>
K

#include <string>
P.

using namespace std;

int main() {

ifstream file("sample.txt");

string word;

int count = 0;
File Handling Compiled by chara1 Petros Psuedo

while (file >> word) {

count++;

file.close();

cout << "Number of words: " << count << endl;

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

̊ Count Characters in a File

#include <iostream>
h
#include <fstream>
ac

using namespace std;


ar

int main() {

ifstream file("sample.txt");
h

char ch;
.C

int count = 0;

while (file.get(ch)) {
K

count++;
P.

file.close();

cout << "Number of characters: " << count << endl;

return 0;

}
File Handling Compiled by chara1 Petros Psuedo

ͧ How it works:

 file.get(ch) reads one character at a time


 This includes letters, numbers, spaces, punctuation, etc.

˪ Count a Specific Word (e.g., “apple”)

#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

while (file >> word) {


ar

if (word == target) {

count++;
h

}
.C

file.close();
K

cout << "The word '" << target << "' appears " << count << " times." << endl;
P.

return 0;

Tips for Beginners

 Always close() the file after you use it.


 Always check if the file exists before reading (or it may crash).
 Try with different inputs in sample.txt and see how counts change.
 You can also cout << word; inside the loop to see what’s being read.
File Handling Compiled by chara1 Petros Psuedo

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.

We’ll walk through:

Ž Part 1: Let the User Enter Text and Save It to a File

Goal:

 Ask the user to type multiple lines


 Save those lines in a file (e.g., input.txt)

e
ˇ Code:

w
#include <iostream>

#include <fstream>

im
#include <string>

using namespace std;


h
int main() {
ac

ofstream file("input.txt"); // Open file to write

string line;
ar

cout << "Enter text (type 'END' to stop):\n";


h

while (true) {
.C

getline(cin, line);

if (line == "END") break; // Stop when user types END


K

file << line << endl; // Save to file


P.

file.close();

cout << "Text saved to file.\n";

return 0;

Explanation:
File Handling Compiled by chara1 Petros Psuedo

 getline(cin, line): Reads a full line from user input


 "END" is used as a stop word (you can choose anything)
 file << line << endl; writes each line to the file
 User can type as many lines as they want

Ž Part 2: Now Count What’s Inside the File

Let’s say we now want to:

 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

cout << "Enter your text (type 'END' to stop):\n";


.C

while (true) {
K

getline(cin, line);

if (line == "END") break;


P.

file << line << endl;

file.close();

void countLines() {
File Handling Compiled by chara1 Petros Psuedo

ifstream file("input.txt");

string line;

int count = 0;

while (getline(file, line)) {

count++;

file.close();

e
w
cout << "Total lines: " << count << endl;

im
void countWords() {

ifstream file("input.txt");
h
string word;
ac

int count = 0;

while (file >> word) {


ar

count++;
h

file.close();
.C

cout << "Total words: " << count << endl;


K

}
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();

cout << "Total characters: " << count << endl;

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;

cin.ignore(); // Clears leftover input


h
switch (choice) {

case 1: getUserInput(); break;


ac

case 2: countLines(); break;


ar

case 3: countWords(); break;

case 4: countCharacters(); break;


h

default: cout << "Invalid choice!\n";


.C

return 0;
K

}
P.

How it Works

1. Run the program


2. Choose:
o 1 to enter text
o 2, 3, or 4 to analyze the file
3. It saves the input into input.txt, and uses that file to count

ӑ Try It!
File Handling Compiled by chara1 Petros Psuedo

 Try entering:

Hello there

I love coding

END

 Then choose options 2–4 to count the data


 Counting blank spaces (spaces ' ' between words) is another useful skill in file
handling.

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

Code: Count Blank Spaces in a File

#include <iostream>
h

#include <fstream>
.C

using namespace std;

int main() {
K

ifstream file("input.txt"); // open file to read


P.

char ch;

int spaceCount = 0;

if (!file) {

cout << "File could not be opened.\n";

return 1;

}
File Handling Compiled by chara1 Petros Psuedo

while (file.get(ch)) {

if (ch == ' ') {

spaceCount++;

file.close();

cout << "Number of blank spaces: " << spaceCount << endl;

e
w
return 0;

im
ͧ Explanation:

 file.get(ch) reads one character at a time



h if (ch == ' ') checks if that character is a space
 spaceCount++ adds 1 for each space found
ac

Add to Your Menu Program?

Want to add this option to the menu you already have?


ar

Here’s the function you can add:


h

void countSpaces() {

ifstream file("input.txt");
.C

char ch;
K

int count = 0;
P.

while (file.get(ch)) {

if (ch == ' ') count++;

file.close();

cout << "Total spaces: " << count << endl;

}
File Handling Compiled by chara1 Petros Psuedo

And in main():

cout << "5. Count Spaces\n";

Then add:
case 5: countSpaces(); break;
Ž Final Tips

 You can also count tabs with if (ch == '\t')


 Or count newlines with if (ch == '\n')
 You can count punctuation too using ispunct(ch)

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

More Detailed Explanation

In main(), we usually end with:


h

return 0; // Everything worked fine


.C

But if something goes wrong (like a file fails to open), we use:


K

return 1; // Signal an error happened


Why Use 1 and Not 0?
return value Meaning
P.

Success (program This is a convention that the operating system


0 or shell uses to know if your program worked.
OK)

Error (something Ӑ Example:


1 (or other)
failed)
Imagine running your program in the terminal
like this:

./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 $?

This will show:

 0 if the last program ended successfully


 1 (or something else) if there was an error

Ž When to Use It in C++ Programs

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.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy