File Handling
File Handling
SAROJ SHARMA
File
File is a collection of information, usually stored on a computer’s disk.
Information can be saved to a file and then later reused.
Files are assigned two things:
Name
Extension
Advantages of using file/why needed
Convenient way to deal large quantities of data.
Store data permanently (until file is deleted).
Avoid typing data into program multiple times.
Share data between programs.
We need to know:
how to "connect" file to program
how to tell the program to read data
how to tell the program to write data
error checking and handling EOF
stream
Stream is the flow of digital data(bytes) as input or output through an abstract device(for example screen, keyboard, files
etc).In other words, Link between program and files is called stream.
The sequence of bytes given as input to the executing program and the sequence of bytes that comes as output from the
executing program are called stream
Write data to file
Read data from file
Disk file
Output Input
stream stream
Program
Data output Data input
Named based on data coming or going out of program
Keyboard
Input Stream Hard disk
Output Stream
Program File
Input Stream
Output Stream
Screen
Hierarchy of the system
Process of using a file
The file must be opened. If the file doesn’t exist, opening a file will create a new one.
information is then saved to the file and read from the file or both.
Finally the file must be closed.
Main functions used in file handling
open() to create a file
close() to close an existing file
get() to read a single character from a file
put() to write a single character into the file
read() read data from file
write() write data into file
Header files required for stream processing
Ex:ifstream ifs;
We are creating an object of ifstream class. i.e. creating a link now from program to file to
supply input to the file
\
Open file
To open a file, we must first create a file stream and link it to the filename.
A file stream can be defined using the classes ifstream,ofstream and fstream that are contained
in the header file fstream.
The class to be used depends upon the purpose that is, whether we want to read data from the
file or write data to it.
There are two ways to open the file
◦ 1.using the constructor: useful when we use only one file in the stream.
◦ 2.using member function open of fstream or ostream: used when we want to manage
multiple files using one stream.
Using constructor
Ofstream ofs(“filetowrite.txt”)
Opening in different location
Using the member function open() of the
class
Step1:Create stream object
Ofstream ofs;
ios::ate | ios::binary
Default actions
Open for reading only H E L L O W O R L D
Input pointer
output pointer
output pointer
Specifying the offset
Seek call Action
fin.seekg(0,ios::beg); Go to start
fin.seekg(0,ios::cur); Stay at the current position
fin.seekg(0,ios::end); Go to the end of file
fin.seekg(m,ios::beg); Move to (m+1)th byte in the file
fin.seekg(m,ios::cur); Go forward by m bytes from the current position
fin.seekg(-m,ios::cur); Go backward by m bytes from the current position
fin.seekg(-m,ios::end); Go backward by m bytes from the end
Read and write
Write an object of a class to this file, by using the write() function.
write( (char *) & object, sizeof(object));
Read the stored object from the file, by using the read() function.
first you take the address of the object using the & (the address-of operator).
Next you cast it to a char*.
The char* would point to the first byte of the object and write knows how many bytes big the object is based
on you passing sizeof() as the second argument.
ostream::write is an unformatted output function. Unformatted in this case means it's blindly writing
out whatever bytes you give it.
read() and write()
Binary input/output functions named read() and write().
This binary function is used to perform file input operation i.e. to read the objects
read() stored in a file.
This binary function is used to perform file output operation i.e. to write the objects to
write
a file, which is stored in the computer memory in a binary form.
Only the data member of an object are written and not its member functions
Functions for manipulation of file pointers
The file stream classes support the following functions to help us take control of the movement of
the file pointers ourselves:
◦ seekg() – moves get pointer(input) to a specified location.
◦ seekp() – moves the put pointer(output) to a specified location.
◦ tellg() – gives the current position of the get pointer.
◦ tellp() – gives the current position of the put pointer.
Every file maintains two pointers called get_pointer (in input mode file) and put_pointer (in output mode
file) which tells the current position in the file where reading or writing will takes place.
ios::beg, // refers to the beginning of the file
ios::cur, // refers to the current position in the file
ios::end} // refers to the end of the file
Writing to a file
#include <iostream>
#include <fstream>
using namespace std;
int main() {
fstream my_file;
my_file.open("writeFile.txt", ios::out);// in write
mode
if (!my_file) {
cout << "Unable to create!";
}
else {
cout << "File created successfully!";
my_file << "Hello world";
my_file.close();
}
return 0;
}
Reading from file
#include <iostream>
#include <fstream>
using namespace std;
int main() {
fstream my_file;
my_file.open("writeFile.txt", ios::in);
if (!my_file) {
cout << "No such file";
}
else {
char ch;
while (1) {
my_file >> ch; // fetch by characters and put to ch
if (my_file.eof()){
break;
}
cout << ch;
}
}
my_file.close();
return 0;
}
Checking for failure
Ifstream ifs;
Ifs.open(“try.txt”)
if(ifs.fail()){ or if(!ifs)
Cout<<“file cannot be opened”;
Exit(0);
}
Eof
Eof is a member function : last character
If you read character by character
If you encounter the last character, this member function returns true, so returning true
means the loop will be existed.
While(!eof)
◦ Since eof returns true
Writing into a file
cin.get(string_name_to_access, size);
eof() returns TRUE if no more data to be read from an input file stream,keeps reading as
eof() return FALSE until characters are there
cin.get() is used for accessing character array. It includes white space characters. As cin>>
terminates when white space is found
#include<iostream>
#include<stdio.h>
#include<fstream>
#include<string>
#include<conio.h>
using namespace std;
class student
{
public:
int roll;
char name[20];
void createRecord();
void readRecords();
void deleteRecords();
float salary;
void display()
{
cout<<roll<<"\t"<<name<<"\t"<<salary<<"\t"<<endl;
}
};
void student::createRecord()
{
Thank you
get() and put() functions- character io
#include<iostream>
#include<fstream>
using namespace std;
int main() The get() function reads a single character from the associated stream
{ and puts that value in ch
ifstream is; It returns a reference to the stream.
is.open("filename.txt", ios::in); This value will be null if the end of the file is reached.
char ch;
while(!is.eof()) // read until ifstream is not empty
{
ch = is.get();
cout<<ch;
}
is.close();
return 0;
}
put()
int main()
The put() function is used to write a character(at a time) to a file. {
ofstream of;
of.open("File2.txt", ios::out);
char arr[100] = "Hello World.";
int length = strlen(arr);
char ch;
for(int i=0; i<length; i++)
{
ch = arr[i];//putting one char is not
need to assign to array
of.put(ch); //Writing a char
file, by using put() function
}
of.close();
return 0;
}
#include <iostream.h>
using namespace std;
int main()
{
int count=0;
char c;
cout<<”INPUT TEXT \n”;
cin.get( c );
while ( c !=’\n’ )
{ cout.put( c);
count++;
cin.get( c );
}
cout<< “\n Number of characters =” ----”\n”;
return 0;
}
//C++ Reading the content to a file using ifstream class and file mode ios::in
#include<iostream>
#include<ifstream>
using namespace std;
int main()
{
//Creating an input stream to read a file
ifstream ifstream_ob;
//Opening a file named File1.txt to read its content
ifstream_ob.open("File1.txt", ios::in);
char ch;
//Reading the file using get() function and displaying its content
while(ifstream_ob)
{
ch = ifstream_ob.get();
cout<<ch;
}
//Closing the input strea
ifstream_ob.close();
return 0;
}
https://cplusplus.com/doc/tutorial/files/
https://cpphinditutorials.com/dev-cpp/file-handling-examples-in-cpp/#
To_Delete_Record_From_a_file
http://www.cppforschool.com/tutorial/files2.html