File Handling
File Handling
(24ECE2101)
Teaching Team
• The two types of file pointers are read pointer and the write
pointer.
• While the read pointer is called, the get pointer specifies a
location from where the current read operation is initiated.
• The write or the put pointer specifies a location from where the
current write operation is initiated.
• Once the read or write operation is completed, the appropriate
pointer is automatically advanced.
FILE POINTERS AND THEIR MANIPULATORS
Manipulating File Pointers
Specifying the Offset
9
Guess the output?
10
Guess the output?
11
Guess the output?
12
Guess the output?
Explanation:
•"1234567890" has 10
characters.
•in.seekg(-3, ios::end) moves the
get pointer to the 7th character
(index 7 = '8').
•Then in.get(ch) reads the
character at that position.
13
Guess the output?
14
Specifying the Offset
get() and put() functions
• The get() reads a single
character from the
associated stream and
the put() is used to
write a single character
to the associated
stream.
• Hobby.txt must already
exits.
ERROR HANDLING DURING FILE OPERATIONS
a. fileObject.tellg( ios::cur, n );
b. fileObject.tellg( n, ios:cur );
c. fileObject.seekg( n, ios::cur );
d. fileObject.seekg( ios:cur, n );
Answer: c
fileObject.seekg( n, ios::cur );
Quiz Time
Answer: b
Quiz Time
Answer: c
Quiz Time
What will happen if the file "test.txt" does not exist when
outfile.open("test.txt") is called?
Answer: c
Quiz Time
Quiz Time
a. This is an apple
b. apple
c. sample
d. This is a sample
Answer: d
Quiz Time
Answer: b
Quiz Time
A) 12345
B) 1 2 3 4 5
C) 1\n2\n3\n4\n5
D) 1, 2, 3, 4, 5
Answer: b
Quiz Time
A) Runtime error
B) File opened successfully
C) File does not exist
D) Nothing is printed
Answer: c
Quiz Time
30
Quiz Time
31
Check the output?
#include <fstream.h>
void main()
{
int marks[] = {98, 67, 89, 100, 45, 65, 51, 78, 12, 43};
int arr[10] = {0};
fstream FILE; // create object
Write a C++ program to count the number of characters and the number of
lines in a text file.
📌 Requirements:
1.The program should prompt the user to enter the filename.
2.It should open the file in read mode.
3.If the file does not exist or cannot be opened, display an error message.
4.If the file opens successfully:
•Count the total number of characters in the file (including spaces and
newline characters).
•Count the number of lines (each line ends with a newline character
\n).
5.Display the total number of characters and lines in the file.
6.If the file is empty, display an appropriate message.
34
Thanks