0% found this document useful (0 votes)
13 views

Lecture_9 File Processing

Uploaded by

Ahmed Ali
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Lecture_9 File Processing

Uploaded by

Ahmed Ali
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Computer Programming

Lecture 9
File Processing
Using Input/Output Files
A computer file
is stored on a secondary storage device (e.g., disk);
is permanent
File handling provides a mechanism to store the output of
a program in a file and to perform various operations on
it.
In C++, files are mainly dealt by using three classes
fstream, ifstream, ofstream available in fstream
headerfile.

8.2
Using Input/Output Files

Class Description

ifstream It is used to read information from files.

It is used to create files and write information


ofstream
to the files.

It is used to create files, write information to


fstream
files, and read information from files.

8.3
Text and Binary Files
A text file stores data in the form of alphabets, digits
and other special symbols by storing their ASCII values
and are in a human-readable format. for example, any
file with a .txt, .cpp, .html extension.

Binary files are those typical files that store data in the
form of sequence of bytes grouped into eight bits or
sometimes sixteen bits. These bits represent custom
data and such files can store images, audio under a
single file.

8.4
Binary VS Text Files

Text File Binary File


8.5
In text files, each line of text is terminated with a special
character known as EOL (End of Line) character or
delimiter character.

8.6
Binary VS Text Files
Text File Binary File

Bits represent character. Bits represent a custom data.

Less prone to get corrupt as changes


Can easily get corrupted, even a
reflect as soon as the file is opened
single bit change may corrupt the file.
and can easily be undone.

Can store different types of data


Can store only plain text in a file.
(image, audio, text) in a single file.

Developed especially for an


Widely used file format and can be
application and may not be
opened using any simple text editor.
understood by other applications.

Mostly .txt and .rtf are used as Can have any application defined
extensions to text files. extension.
8.7
Operations in File Handling

C++ provides us with the following operations in File


Handling:

 Creating/Opening a file: open()

 Reading data: read()

 Writing data: write()

 Closing a file: close()

8.8
Creating/Opening a file
A File must be opened before we can read from it or write
to it. We can use ifstream object to open a file for writing
or reading purpose.
Following is the Standard Syntax to Open File.

fstream myFile;
myFile.open("filename.txt", ios::openMode);

• Where filename.txt is a string representing the name of the


file to be opened, and openMode is an optional parameter with a
combination of the flags in next slide…

8.9
Open Modes
Modes Meaning Description

Opens the file to read


in Read
(if the file don't exist, it will generate an error)

Opens the file to write


out Write (if the file already exist, then it will be formated)
(If there is no file exist, then this mode will create New file)

binary Binary Opens the file in binary mode


Opens the file and appends all the outputs at the
app Appending
end (we can write only at the end of the file)

Opens the file and moves the control to the end of


ate Appending
the file (we can write any where in File)

trunc Truncate Removes the data in the existing file

nocreate Don't Create Opens the file only if it already exists

noreplace Don't Replace Opens the file only if it does not already exist 8.10
the header
the header file fstream be included in the program. The
following statement accomplishes this task:
#include <fstream>

8.11
Example
fstream myfile;
myfile.open("newfile.txt", ios::out);
In the above example, myfile is an object of type fstream, as we
know fstream is a class so we need to create an object of this class to
use its member functions. So we create new_file object and call
open() function.
❑ Example of file opened for writing:
myfile.open("E:\studytonight.txt",ios::out);

❑ Example of file opened for reading:


myfile.open("E:\studytonight.txt",ios::in);

❑ Example of file opened for appending:


myfile.open("E:\studytonight.txt",ios::app);

❑ Example of file opened for truncating:


myfile.open("E:\studytonight.txt",ios::trunc);
8.12
Example of Opening/Creating a file
Here we first create a new file “new_file” using open() function
#include <iostream>
#include <fstream>
using namespace std; The out mode allows
int main() { us to write into the file

fstream myfile;

myfile.open("new_file.txt",ios::out);
if(!myfile) if statement to check
{ whether file creation failed
cout<<"File creation failed";
}
else
{
cout<<"New file created";
myfile.close();
the close() function
}
system("pause"); for closing the file
return 0;
} 8.13
IO operations
Reading / Writing Data to/from files

Data Reading Writing

char get(); put();

1 word >> <<

>=1
getline(); <<
word

Objects read() write()

8.14
Formatted IO operations

Formatted IO operations are supported via the stream


insertion (<<) and stream extraction (>>) operators.

In formatted or high-level IO, bytes are grouped and


converted to types such as int, double, string or user-
defined types.

8.15
Writing to a Text File
Simply use the << and >> operators the same way you do when
performing console I/O
#include <iostream>
#include <fstream>
using namespace std; The out mode allows
us to write into the file
int main() {
fstream myfile;
myfile.open("new_file.txt",ios::out);
if(!myfile)
{
cout<<"File creation failed";
} Write to the file
else
{
cout<<"New file created";
myfile << "Book1 " << 39.95 << endl;
myfile << "Book2 " << 19.95 << endl;
myfile << "Book3 " << 24.80 << endl;
myfile.close();
}
system("pause");
return 0;
}
8.16
Reading from a Text File
#include <string>
#include <iostream> The following program reads the file that
#include <fstream> created by the previous program and
using namespace std;
displays its contents on the screen
int main() {
string item;
float cost;
fstream myfile;
myfile.open("new_file.txt",ios::in);
if(!myfile) The in mode allows us to
{
cout<<"File creation failed";
read from the file
}
else
{
Read from the file
myfile >> item >> cost;
cout << item << " " << cost << "\n";
myfile >> item >> cost;
cout << item << " " << cost << "\n";
myfile >> item >> cost;
cout << item << " " << cost << "\n";

myfile.close();
}
system("pause");
return 0;
} 8.17
Unformatted IO operations
In unformatted or low-level IO, bytes are treated as raw
bytes and unconverted.
Unformatted input functions are get(), getlin(), read().
The unformatted output functions are put(), write().
get( ) will read a single character and put( ) will write a
single character.
getline() it read whole line of text that end with newline
character.

8.18
Reading a file using getline()
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
int main() {
string item;
fstream myfile;
myfile.open("new_file.txt",ios::in);
if(!myfile)
{
cout<<"File creation failed";
}
else
{
getline(myfile,item); Read from the file
cout << item << endl;
getline(myfile,item);
cout << item << endl;
getline(myfile,item);
cout << item << endl;

myfile.close();
}
system("pause");
return 0;
}

8.19
Detecting the End of a File (eof)
Member function eof detects the end of a file
Member function of every input-file stream
eof stands for end of file
eof returns a boolean value
True when the end of the file has been reached
False when there is more data to read
Normally used to determine when we are NOT
at the end of the file
Example: if ( !file.eof( ) )

8.20
Program to count number of characters
#include <string>
#include <iostream>
#include <fstream>
using namespace std;

int main() {
ifstream myfile;
myfile.open("new_file.txt");

int count = 0;
char ch;
read till end-of-file
while(!myfile.eof())
{
myfile.get(ch); read a single character
count++;
}

cout << "Number of characters in file are " << count <<endl;
myfile.close();

system("pause");
return 0;
}

8.21
Multiple Choice Questions
1. Which header file is required to use file I/O operations?
a) <ifstream>
b) <ostream>
c) <fstream>
d) <iostream>

2. Which of the following is used to create an output


stream?
a) ofstream
b) ifstream
c) iostream
d) fsstream

8.22
Multiple Choice Questions
3. Which of the following is used to create a stream that
performs both input and output operations?
a) ofstream
b) ifstream
c) iostream
d) fstream

4. Which of the following is not used as a file opening


mode?
a) ios::trunc
b) ios::binary
c) ios::in
d) ios::ate
8.23
Multiple Choice Questions
5. By default, all the files in C++ are opened in
_________ mode.
a) Text
b) Binary
c) ISCII
d) VTC

6. What is the use of ios::trunc mode?


a) To open a file in input mode
b) To open a file in output mode
c) To truncate an existing file to half
d) To truncate an existing file to zero

8.24
Multiple Choice Questions
7. Which of the following is the default mode of the
opening using the ofstream class?
a) ios::in
b) ios::out
c) ios::app
d) ios::trunc

8. 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 Answer : b How?
8.25
Multiple Choice Question
9. Which operator is used to insert the data into file?
a) >>
b) <<
c) <
d) >

10. Which is correct syntax ?


A) myfile:open ("example.bin", ios::out);
b) myfile.open ("example.bin", ios::out);
c) myfile::open ("example.bin", ios::out);
d) myfile.open ("example.bin", ios:out);

8.26
Multiple Choice Questions
11. What is use of eof() ?
Returns true if a file open for reading has reached the next character.
Returns true if a file open for reading has reached the next word.
Returns true if a file open for reading has reached the end.
Returns true if a file open for reading has reached the middle.

8.27
Assignment
1) Write a C++ program to write number 1 to 100 in a data
file named “Numbers.txt”

2) Write a function to count number of words in a text file


named “Words_count.txt".

8.28

You might also like