Data File Handling in C++ for Class 12th Computer Science – CBSE
Stream: We can think of a stream as a channel or conduit on which data is passed from senders to receivers. Data can be sent out from the program on an output stream, or received into the program on an input stream.
For example, at the start of a program, the standard input stream “cin” is connected to the keyboard and the standard output stream “cout” is connected to the screen.
File: A file is just a bunch of bytes stored on some storage devices like hard disk, pen drive etc. Some have a specific structure others don’t. Files are used to save info so that it can be retrieved later for use.
Need of Files:
If we were restricted to use only the keyboard and screen as input and output devices, it would be difficult to handle large amounts of input data, and output data would always be lost as soon as we turned the computer off. To avoid these problems, we can store data in some secondary storage device, usually on hard disks or discs or pen drives. Data can be created by one program, stored on these devices, and then accessed or modified by other programs when necessary. To achieve this, the data is packaged up on the storage devices as data structures called files.
If we were restricted to use only the keyboard and screen as input and output devices, it would be difficult to handle large amounts of input data, and output data would always be lost as soon as we turned the computer off. To avoid these problems, we can store data in some secondary storage device, usually on hard disks or discs or pen drives. Data can be created by one program, stored on these devices, and then accessed or modified by other programs when necessary. To achieve this, the data is packaged up on the storage devices as data structures called files.
Types of Files:
Generally there are two types of files in C++:
- Text Files: A text file is usually considered as sequence of lines. Line is a sequence of characters stored on permanent storage media. Each line is terminated by a special
character, known as End of Line (EOL). - Binary Files: Data is stored in binary form or in machine language. This data is in non-readable form.
Classes or Header Files Essential for Data File Handling:
There are three file I/O classes used for file read / write operations.
1. ifstream – can be used for read operations.(Open the file for Input)
2. ofstream – can be used for write operations. (Open the file for Output)
3. fstream – can be used for both read & write operations. (Open the file for Input/Output/both)
1. ifstream – can be used for read operations.(Open the file for Input)
2. ofstream – can be used for write operations. (Open the file for Output)
3. fstream – can be used for both read & write operations. (Open the file for Input/Output/both)
fstream.h: This header file includes the definitions for the stream classes ifstream, ofstream and fstream. In C++ file input output facilities implemented through fstream.h header file. It contains predefined set of operation for handling file related input and output, fstream class ties a file to the program for input and output operation.
Opening a File for Input or Output:
A file in C++ can be opened in the following two ways-
- By the constructor method. The constructors of a stream classes (ifstream, ofstream, or fstream) are used to initialize the file stream objects with the file names passed to them. This method is preferred when file is opened in input or output mode only.To open a data file, as an input file (i.e. data will be read from it and no other operation like writing or modifying would take place on the file), we shall create a input file stream object i.e., ifstream type:ifstream file_Input(“Data File”);The above statement creates an object i.e. file_Input of ifstream class. The object name is a user defined name (i.e. any valid identifier name). After creating the ifstream object file_Input, the Data File is opened and is attached to the input stream file_Input.
Similarly, we can also create objects of ofstream class to open a data file for writing purpose.
NOTE: Opening a file for output using stream class constructor creates a new file if there is no file of that name on the disk. However, if the file by that name exists already, then the contents of that file will be overwritten.
NOTE: Opening a file for output using stream class constructor creates a new file if there is no file of that name on the disk. However, if the file by that name exists already, then the contents of that file will be overwritten.
- By using the open() member function the streams-
It will be preferred in when file is opened in various modes i.e. ios::in, ios:out, ios::app etc. It is also used while working with two or more files in a program.
Here, initially we needs to create a stream object, before using it or opening it. Statements to create streams look like variable declarations, and are usually placed at the top of programs or function implementations along with the variable declarations.
For example:
ofstream out_stream;
This will create a stream (or object) called “out_stream” belonging to the class (like type) “ofstream” (output-file-stream).
This will create a stream (or object) called “out_stream” belonging to the class (like type) “ofstream” (output-file-stream).
Now, to open it or to connect this stream object to a data file, we will use open() method of ofstream class. So, to connect the ofstream “out_stream” to the file “inherit.txt”, we use the following statement:
out_stream.open(“inherit.txt”);
Although this connects “out_stream” to “inherit.txt”, it also deletes the previous contents of the file, ready for new input. So, if we want to append the new contents to a file we will use different modes provided in C++.
For example:
out_stream.open(“inherit.txt”, ios::app);
Now, after using this mode i.e. ios::app the “inherit.txt” will be opened in append mode & the previous contents will not be overwritten.
Closing a File:
Closing a File:
A file is closed by disconnecting it with the stream it is associated with. The close() function is used to close an opened file.
Syntax: stream_object.close();
out_stream.close();
out_stream.close();
FILE MODES
The file mode describes how a file is to be used: to read it, to write it, to append it, and so on. File mode is used with open() of the stream class.
Syntax:
stream_object.open(“filename”, (filemode));
ios::out It open file in output mode i.e write mode and place the file pointer in beginning, if file already exist it will overwrite the file.
ios::in It open file in input mode i.e. read mode and permit reading from the file.
ios::app It open the file in write mode, and place file pointer at the end of file i.e to add new contents and retains previous contents. If file does not exist it will create a new file.
ios::ate It open the file in write or read mode, and place file pointer at the end of file.
ios::trunc If the file is opened for output operations and is already existed, its previous content is deleted and replaced by the new one.
ios::nocreate If file does not exist this file mode ensures that no file is created and open fails.
ios::in It open file in input mode i.e. read mode and permit reading from the file.
ios::app It open the file in write mode, and place file pointer at the end of file i.e to add new contents and retains previous contents. If file does not exist it will create a new file.
ios::ate It open the file in write or read mode, and place file pointer at the end of file.
ios::trunc If the file is opened for output operations and is already existed, its previous content is deleted and replaced by the new one.
ios::nocreate If file does not exist this file mode ensures that no file is created and open fails.
ios::noreplace If file does not exist, a new file gets created but if the file already exists, the open fails.
ios::binary Opens a file in binary mode.
ios::binary Opens a file in binary mode.
The default mode is text mode when a file is opened.
All these flags can be combined using the bitwise operator OR (|). For example, if we want to open the file “example.bin” in binary mode to add data we could do it by the following call to member function open:
ofstream myfile;
myfile.open (“example.bin”, ios::out | ios::app | ios::binary);
All these flags can be combined using the bitwise operator OR (|). For example, if we want to open the file “example.bin” in binary mode to add data we could do it by the following call to member function open:
ofstream myfile;
myfile.open (“example.bin”, ios::out | ios::app | ios::binary);
Each of the open member functions of classes ofstream, ifstream and fstream has a default mode that is used if the file is opened without a second argument:
class default mode parameter
ofstream ios::out
ifstream ios::in
fstream ios::in | ios::out
ofstream ios::out
ifstream ios::in
fstream ios::in | ios::out
Writing to a File
Steps:
- Create object of ofstream class.
ofstream file1; - Open a file with this object.
file1.open (“names.txt”,ios::app );
- Write in the file (Different ways or methods)
file1<<”APJ KALAM”; - Close the opened file using close() function.
file1.close();
Example:
// Simple example to write in a file
#include <fstream>
int main()
{
ofstream file1;
file1.open(“names.txt”, ios::app);
file1<< ”APJ KALAM”;
return 0;
}
{
ofstream file1;
file1.open(“names.txt”, ios::app);
file1<< ”APJ KALAM”;
return 0;
}
Different methods for writing in a file
- put() – This function is used for writing a single character in file.
file1.put(‘c’);
- Insertion operator (<<) – This operator is also used to write in a file.
file1<<”APJ KALAM”;
Reading from a File
Steps:
- Create object of ifstream class.
ifstream fileInput; - Open a file with this object.
fileInput.open (“names.txt” );
- Read from the file (Different ways or methods)
char arr[20];
fileInput>>arr;
cout<<arr; - Close the opened file using close() function.
fileInput.close();
Example:
// Simple example to read from a file
#include <fstream>
int main()
{
ifstream fileInput;
char arr[20];
fileInput.open(“names.txt”);
fileInput >> arr;
cout<<arr;
return 0;
}
Different methods for reading from a file
int main()
{
ifstream fileInput;
char arr[20];
fileInput.open(“names.txt”);
fileInput >> arr;
cout<<arr;
return 0;
}
Different methods for reading from a file
- get() – This function is used for reading a single character or a string in a file.
- fileInput.get(‘c’);
or
char arr[10];
char arr[10];
fileInput.get(arr, 10 );
- Extraction operator (>>)- This operator is also used to read from a file.
- char arr[20];
fileInput >>arr;
- getline()- It reads characters from input stream and puts them in the array pointed to by the buff until either num charcters have been read, or character specified by delim is encountered. If not mentioned, the default value of delim is newline character.syntax: istream & getline(char * buf, int num, char delim=’\n’)char arr[20];fileInput.getline(arr, 20);
or
fileInput.getline(arr, 20, EOF);
SIMPLE PROGRAMS
Q1. To create a File using string Input.
int main()
{
char str[100];
ofstream out_obj(“FileInput.txt”);
cout<<“Enter Text: “;
cin.getline(str, sizeof(str));
out_obj<<str;
out_obj.close();
}
char str[100];
ofstream out_obj(“FileInput.txt”);
cout<<“Enter Text: “;
cin.getline(str, sizeof(str));
out_obj<<str;
out_obj.close();
}
Q2. To copy the contents of a file “Input.txt” into another file “Output.txt”
Q3. Write a function in C++ to count the number of lowercase alphabets present in a text file “BOOK.txt”.
int main()
{
char ch; int c=0;
ifstream input(“BOOK.txt”);
while(input.get(ch))
{
if(islowercase(ch))
c++;
}
cout<<”No. of lowercase alphabets: ”<<c<<endl;
}
{
char ch; int c=0;
ifstream input(“BOOK.txt”);
while(input.get(ch))
{
if(islowercase(ch))
c++;
}
cout<<”No. of lowercase alphabets: ”<<c<<endl;
}
Q4. Write a function in C++ to read the content of a text file “DELHI.TXT” and display all those lines on screen, which are either starting with ‘D’ or starting with ‘M’.
void fun()
{
char str[100];
ifstream in(“DELHI.txt”);
while(in.getline(str,100))
{
if(str[0]==’M’||str[0]==’D’)
cout<<str<<endl;
}
}
{
char str[100];
ifstream in(“DELHI.txt”);
while(in.getline(str,100))
{
if(str[0]==’M’||str[0]==’D’)
cout<<str<<endl;
}
}
NOTE: Simplified for class XII CBSE students.