Lecture 3.3.2 Reading and Writing To Files Random Access To Files
Lecture 3.3.2 Reading and Writing To Files Random Access To Files
Course Objectives
2
Course Outcomes
CO Course Outcome
Number
CO1
Understand the concepts of object-oriented programming
including programming process and compilation process.
CO2
Apply different techniques to decompose a problem and
programmed a solution with its sub modules.
CO3
Analyze and explain the behavior of simple programs involving the
programming addressed in the course.
CO4 Implement and evaluate the programs using the syntax and
semantics of object-oriented programming.
CO5
Design the solution of real-world problems in order to determine
that the program performs as expected.
3
Scheme of Evaluation
4
CONTENTS
• Reading/Writing of
files
• Random-access to
files.
• Examples
5
Writing data to Files (file output)
• Once declared we can use file streams normally in the same
fashion we have used cout and cin streams
6
Writing data to Files (file output)
• This code creates a file called TestFile.txt and inserts a sentence into
it, the same way we are used to do with cout, but using the file
stream MyOutputStream instead.
7
Writing data to Files (file output)
• Filename & mode can be provided to the constructor of stream class,
instead of calling open() method explicitly.
8
Writing data to Files (file output)
• As we know mode is optional for ofstream and ifstream, so its not
necessary to specify it. Specify only file name to be open
9
Example 2:How to Write to Files
10
Example of writing to a file
#include <iostream>
#include <fstream>
using namespace std;
int main() {fstream my_file;
my_file.open("my_file.txt", ios::out);
if (!my_file) {
cout << "File not created!"; }
else {
cout << "File created successfully!";
my_file << "Guru99";
my_file.close();
}
return 0;
} 11
Output
12
Explanation of the Code
1.Include the iostream header file in the program to use its functions.
2.Include the fstream header file in the program to use its classes.
3.Include the std namespace in the program to use its classes without
calling it.
4.Call the main() function. The program logic should be added within
the body of this function.
5.Create an instance of the fstream class and give it the name my_file.
6.Use the open() function to create a new file named my_file.txt. The
file will be opened in the out mode for writing into it.
7.Use an if statement to check whether the file has not been opened.
8.Text to print on the console if the file is not opened. 13
9. End of the body of the if statement.
10. Use an else statement to state what to do if the file was created.
11. Text to print on the console if the file was created
12. Write some text to the created file.
13.Use the close() function to close the file.
14. End of the body of the else statement.
15. The program must return value upon successful completion.
16. End of the body of the main() function.
14
Example 3: Writing to a file using the open()
function
Explanation
Here we first create a new file
“new_file_write” using open()
function since we wanted to
send output to the file so, we
use ios::out. As given in the
program, information typed
inside the quotes after
Insertion Pointer “<<” got
passed to the output file.
15
Reading data from Files (file input)
• Data can be retrieved from a file input stream the same way we
read from standard input stream ‘cin’.
16
Example 2: Reading from a file
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream new_file;
new_file.open("new_file_write.txt",ios::in);
if(!new_file)
cout<<"No such file"; } else { char ch; while (!new_file.eof()) { new_file >>ch;
cout << ch;
}
new_file.close();
return 0;
}
17
Output
18
Explanation of the Code
In this example, we read the file that generated id previous example i.e.
new_file_write.
To read a file we need to use ‘in’ mode with syntax ios::in. In the above
example, we print the content of the file using extraction operator >>.
The output prints without any space because we use only one
character at a time, we need to use getline() with a character array to
print the whole line as it is.
19
RANDOM ACCESS IN FILES
• Random Access means non-sequentially accessing information in a
file
20
• In C++, random access is achieved by manipulating seekg(), seekp(),
tellg() and tellp() functions.
• The seekg() and tellg() functions allow you to set and examine the
get_pointer, and the seekp() and tellp() functions perform these
operations on the put_pointer.
21
Each File has two Associated Pointers
Known as File Pointers
• One of them is called the get pointer.
The get pointer specifies a location from which the current reading
operation is initiated
22
Functions for manipulation of File pointers
seekp():It places the file pointer to the specified position in output
mode(ofstream)of file.
seekg(): It places get pointer to the specified location in input mode(ifstream) of file
tellg(): This function returns the current working position of the file
pointer in output mode(ofstream)
tellp(): This function returns the current working position of the file
pointer in the intput mode(ifstream).
23
• The seekg() and tellg() functions are for input streams (ifstream) and
seekp() and tellp() functions are for output streams (ofstream).
However, if you use them with an fstream object then tellg() and
tellp() return the same value. Also seekg() and seekp() work the same
way in an fstream object.
• The working of seekg() & seekp() and tellg() & tellp() is just the same
except that seekg() and tellg() work for ifstream objects and seekp()
and tellp() work for ofstream objects. In the above table, seek_dir
takes the definition enum seek_dir { beg, cur, end};.
24
• ifstream fin;
• ofstream fout; // file opening routine
• fin.seekg(30); // will move the get_pointer (in ifstream) to byte
number 30 in the file
• fout.seekp(30); // will move the put_pointer (in ofstream) to byte
number 30 in the file
25
SPECIAL OPERATIONS
26
Example:
#include<iostream>
#include<fstream>
using namespace std;
int main() {
fstream fp;
char buf[100];
int pos;
// open a file in write mode with 'ate' flag
fp.open("E:\STUDENT.txt", ios :: out|ios::ate);
cout << "\nWriting to a file ... " << endl;
27
Example Contd…
fp << "This is a line and can add another line also"<< endl; // write a
line to a file
//fp << "This is a another line" << endl; // write another file
pos = fp.tellp();
cout << "Current position of put pointer : " << pos << endl;
// move the pointer 10 bytes backward from current position
28
Example Contd…
fp.seekp(-10, ios :: cur);
fp << endl << "Writing at a random location ";
// move the pointer 7 bytes forward from beginning of the file
fp.seekp(7, ios :: beg);
fp << " Hello World ";
fp.close(); // file write complete
cout << "Writing Complete ... " << endl;
// open a file in read mode with 'ate' flag
fp.open("E:\STUDENT.txt", ios :: in | ios :: ate);
cout << "\nReading from the file ... " << endl;
fp.seekg(0); // move the get pointer to the beginning of the file
29
Example Contd…
// read all contents till the end of file
while (!fp.eof()) {
fp.getline(buf, 100);
cout << buf << endl;
}
pos = fp.tellg();
cout << "\nCurrent Position of get pointer : " << pos << endl;
return 0;
}
30
Output
31
Applications
• There is a time when the output generated by compiling and running the
program does not serve the purpose. If we want to check the output of
the program several times, it becomes a tedious task to compile and run
the same program multiple times. This is where file handling comes into
play.
• Saves time: There are certain programs that require a lot of input from
the user. You can easily access any part of the code with the help of
certain commands.
• Portability: You can easily transfer the contents of a file from one
computer system to another without having to worry about the loss of
data.
32
Summary
33
Frequently Asked question
Q1:What is the output of this program?
Note:Includes all required header files
using namespace std;
int main ()
{
char fine, course;
cout << "Enter a word: ";
fine = cin.get();
cin.sync();
course = cin.get();
cout << fine << endl;
cout << course << endl;
return 0;
}
A. Error
B. find
C. This is find
D. Runtime error
Ans: D 34
Q2:Which function is used to position back from the end of file object?
a) seekg
b) seekp
c) both seekg & seekp
d) seekf
Answer: a
35
Q3: It is not possible to combine two or more file opening
mode in open () method.
A. TRUE
B. FALSE
C. May Be
D. Can't Say
Ans : B
36
Assessment Questions:
1. Which of these is the correct statement about eof() ?
A. Returns true if a file open for reading has reached the next character.
B. Returns true if a file open for reading has reached the next word.
C. Returns true if a file open for reading has reached the end.
D. Returns true if a file open for reading has reached the middle.
38
Discussion forum.
TRY THIS!!
Test the methods read() and write() in the Account class. To
do so, write a program called Account_rw.cpp that
initializes an array with account objects and stores the array
in a file
reads the contents of the file to a second array and displays
the accounts in that array to allow you to check them.
Use binary mode for read or write access to the file.
39
REFERENCES
Reference Books
[1] Programming in C by Reema Thareja.
[2] Programming in ANSI C by E. Balaguruswamy, Tata McGraw Hill.
[3] Programming with C (Schaum's Outline Series) by Byron Gottfried Jitender Chhabra, Tata
McGraw Hill.
[4] The C Programming Language by Brian W. Kernighan, Dennis Ritchie, Pearson education.
Websites:
https://www.studytonight.com/cpp/file-streams-in-cpp.php
http://www.infobrother.com/Tutorial/C++/C++-Random-files
https://codescracker.com/cpp/cpp-file-pointers-random-access.htm
YouTube Links:
https://www.youtube.com/watch?v=TF2-F2duY6c&list=PLIY8eNd
w5tW_o8gsLqNBu8gmScCAqKm2Q&index=30
40
THANK YOU