41
Data File Handling in C++

Data File Handling

Embed Size (px)

DESCRIPTION

File handling in c plus plus

Citation preview

Page 1: Data File Handling

Data File Handling in C++

Data File Handling in C++

Page 2: Data File Handling

Introduction Introduction • Computer programs are associated to

work with files as it helps in storing data & information permanently.

• File - itself a bunch of bytes stored on some storage devices.

• In C++ this is achieved through a component header file called fstream.hfstream.h

• The I/O library manages two aspects- as interface and for transfer of data.

• The library predefine a set of operations for all file related handling through certain classes.

Page 3: Data File Handling

• C++ provides a new technique for handling I/O operations through mechanism known as streams.

• A stream refers to a flow of data.• Classified in 2 categories:1. Output stream2. Input streamIn output stream flow of data is from program to the

output device.In input stream the flow of data is from input device to

a program in main memory.

Page 4: Data File Handling

The fstream.h header file

Streams act as an interface between files and programs.

They represent as a sequence of bytes and deals with the flow of data.

Every stream is associated with a class having member functions and operations for a particular kind of data flow.

File Program ( Input stream) - reads

Program File (Output stream) – write

All designed into fstream.h and hence needs to be included in all file handling programs.

Diagrammatically as shown in next slide

Page 5: Data File Handling
Page 6: Data File Handling

Stream Class Hierarchy

ios

ostreamistream

fstream

iostream

ofstreamifstream

User-Defined Streams

System-Defined Streams

Page 7: Data File Handling

Why to use Files:•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 programhow to tell the program to read data

how to tell the program to write dataerror checking and handling EOF

Page 8: Data File Handling

Stream Insertion Operators• Are defined in the ostream class• The operator “<<” is called the inserter

Stream Extraction Operators• Are defined in the istream class and are used to receive data from the input device• The operator “>>”, called the extractor, accepts any built-in data type passed as arguments

Page 9: Data File Handling

1: To access file handling routines:#include <fstream.h>#include <fstream.h>

2: To declare variables that can be used to access file:ifstream in_stream;ifstream in_stream;

ofstream out_stream;ofstream out_stream; 3: To connect your program's variable (its internal name) to an external file (i.e., on the Unix file system):

in_stream.open("infile.dat");in_stream.open("infile.dat");out_stream.open("outfile.dat");out_stream.open("outfile.dat");

4: To see if the file opened successfully:if (in_stream.fail())if (in_stream.fail())

{ cout << "Input file open failed\n";{ cout << "Input file open failed\n"; exit(1);exit(1); // requires <stdlib.h>}// requires <stdlib.h>}

Page 10: Data File Handling

5: To get data from a file (one option), must declare a variable to hold the data and then read it using the extraction operator:

int num;int num;in_stream >> num;in_stream >> num;

[Compare: cin >> num;][Compare: cin >> num;] 6: To put data into a file, use insertion operator:

out_stream << num;out_stream << num;[Compare: cout << num;][Compare: cout << num;]

NOTE: Streams are sequential – data is read and written in order – generally can't back up.

7: When done with the file:in_stream.close();in_stream.close();

out_stream.close();out_stream.close();

Page 11: Data File Handling

Example (creating file)

#include<fstream.h>

#include<process.h>

Void main()

{

int rollno

char name[10];

ofstream ofil(“stud.txt”);

cout<<“enter details”;

cin>>rollno>>name;

cout<<“writing student details into file…..”;

ofil<<rollno<<endl<<name;

getch();

}

Page 12: Data File Handling

Reading a file

#include<fstream.h>

#include<process.h>

Void main()

{

int rollno

char name[10];

Ifstream ifil(“stud.txt”);

If(!ifil)

{

Cout<<“can not open file”;

Exit(-1);

}

Page 13: Data File Handling

cout<<“reading data from file…”;

ifil>>rollno>>name;

cout<<“roll no is”<<rollno<<endl;

cout<<“name is”<<name<<endl;

getch();

}

Page 14: Data File Handling

ios:: app - (append) write all output to the end of file ios:: ate - data can be written anywhere in the file ios:: binary - read/write data in binary format ios:: in - (input) open a file for input ios::out - (output) open a file for output ios:: trunc -(truncate) discard the files’ contents if it exists

File Open Modes

Page 15: Data File Handling

Stream state member functions

•In C++, file stream classes inherit a stream state member from the ios class, which gives out

the information regarding the status of the stream.

For e.g.:eof() –used to check the end of file eof() –used to check the end of file charactercharacterfail()- used to check the status of file at fail()- used to check the status of file at opening for I/Oopening for I/Obad()- used to check whether invalid file bad()- used to check whether invalid file operations or unrecoverable error .operations or unrecoverable error .good()- used to check whether the good()- used to check whether the previous file operation has been previous file operation has been successfulsuccessful

Page 16: Data File Handling

File Input and Output Using ObjectsExample:#include<fstream.h>class student

{

private:

int iReg_no;

char name[20];

public:

void setRegno()

{

Cout<<“registration no”;

Cin>>iReg_no;

}

Page 17: Data File Handling

void setName()

{

Cout<<“enter name”;

Cin>>name;

}

int getRegno()

{

Cout<<iReg_no;

}

char getName()

{

Cout<<name;

}

};

Page 18: Data File Handling

File Input and Output Using Objects (Contd.)void main(){

ofstream Sfil(“studfile.dat”);

char ch;

student Svar;

Svar.setRegno();

Svar.setName();

Sfil<<Svar.getRegno()

<<“ ”<<Svar.getName();

Sfil.close(); //Closes the open file

Page 19: Data File Handling

File Input and Output Using Objects (Contd.)cout<< “\n Do you want to view the contents of a file (y/n)?”;

cin>>ch;if(ch== ‘y’){ifstream Sfil(“studfile.dat”);char ireg;char nam[20];Sfil>>ireg>>nam;cout<<“\n Registration Number is ” <<ireg;cout<<“\n Student Name is ” <<nam;}

}

Page 20: Data File Handling

// Initial experience reading and writing files#include <fstream.h>#include <iostream.h>#include <stdlib.h>int main(){ ifstream in_stream; ofstream out_stream; int num; in_stream.open("numbers.dat"); if (in_stream.fail()) { cout << "Input file could not be opened.\n";

exit(1); } out_stream.open("squares.dat"); if (out_stream.fail()) { cout <<"Output file could not opened.\n";

exit(1); } in_stream >> num; out_stream << "The square of " << num << " is " <<num * num; in_stream.close(); out_stream.close();}

Page 21: Data File Handling
Page 22: Data File Handling

• INPUT AND OUTPUT OPERATION• put() and get() function

the function put() writes a single character to the associated stream. Similarly, the function get() reads a single character form the associated stream.example :file.get(ch);file.put(ch);

• write() and read() functionwrite() and read() functions write and read blocks of data.example:file.read((char *)&obj, sizeof(obj));file.write((char *)&obj, sizeof(obj));

Page 23: Data File Handling

int main()

{

ifstream mys;

char c;

mys.open("new.txt");

if(mys.fail())

{

cout<<"file not found";

}

Page 24: Data File Handling

while (!mys.eof())

{

cout << c;

mys.get(c);

}

mys.close();

getch();

return 0;

}

Page 25: Data File Handling

class Person

{

private:

char name[40];

int age;

public:

void getData()

{

cout << " Enter name:"; cin >> name;

cout << "\n Enter age:"; cin >> age;

}} ;

Page 26: Data File Handling

int main()

{

Person per ;

per.getData();

ofstream outfile("Person.txt");

outfile.write((char*)&per, sizeof(per));

return 0;

getch();}

Page 27: Data File Handling

struct record

{

char player[20];

int age;

int runs;

}emp;

void add()

{

ofstream fp("jk.txt",ios::out);

Page 28: Data File Handling

if(!fp)

{

cout<<"not exits";

exit(1);

}

cout<<"enter name and age and runs";

cin>>emp.player>>emp.age>>emp.runs;

fp.write((char *)&emp,sizeof(emp));

fp.close();

}

Page 29: Data File Handling

void display()

{

ifstream fp("jk.txt",ios::in);

if(!fp)

{

printf("file cannot be opened");

exit(1);

}

printf("records entered");

fp.read((char *)&emp,sizeof(emp));

cout<<emp.player<<" "<<emp.age<<" "<<emp.runs;

fp.close();

}

int main()

{

add();

display();

getch();

return 0;

}

Page 30: Data File Handling

deletionvoid del()

{ int r;

student obj;

ifstream fp1;

ofstream fp2,fp3;

fp1.open("student.dat",ios::in);

fp2.open("temp1.txt",ios::app);

fp3.open("temp2.dat",ios::app);

puts("Enter the deleting roll no.");

cin>>r;

Page 31: Data File Handling

while(fp1.read((char *)&obj,sizeof(obj)))

{

if(r==obj.roll())

{

fp2.write((char *)&obj,sizeof(obj));

}

else

{

fp3.write((char *)&obj,sizeof(obj));

}

}

remove("student.txt");

rename("temp2.txt","student.txt");

getch();}

Page 32: Data File Handling

updatingvoid update()

{

student obj;

int r;

ifstream fp1;

fp1.open("student.txt");

ofstream fp2;

fp2.open("temp.txt",ios::app);

puts("Enter the rollno. to be modified");

cin>>r;

Page 33: Data File Handling

while(fp1.read((char*)&obj,sizeof(obj)))

{

if(obj.roll()==r)

{

puts("Enter new roll no. and name");

obj.getdata();

fp2.write((char*)&obj,sizeof(obj));

}

else

{

fp1.write((char *)&obj,sizeof(obj));

}

}

remove("student.txt");

rename("temp.txt","student.txt");

getch();

}

Page 34: Data File Handling

File pointers

The get Pointer

• Specifies the location in the file where the next read operation will occur

Page 35: Data File Handling

The put Pointer

• Specifies the location in the file where the next write operation will occur

Page 36: Data File Handling

The seekg() Function

• Helps to control the get pointer

• Moves the get pointer to an absolute address within the file or to a certain number of bytes from a particular position

• Takes two arguments:

– The number of bytes to move–The reference in the file from where the pointer has to be repositioned

Example:

ifstream iFil;

iFil.seekg(10,ios::beg);

Page 37: Data File Handling

The tellg() Function

• Helps to control the get pointer

• Can be used to find the current position of the get file pointer in a file

• Does not take any arguments

Example:

int iPosition=iFil.tellg();

Page 38: Data File Handling

The seekp() Function

• Helps to control the put pointer

• Moves the put pointer to an absolute address within the file or to a certain number of bytes from a particular position

Page 39: Data File Handling

The tellp() Function

• Helps to control the put pointer

• Can be used to find the current position of the put file pointer in a file

Page 40: Data File Handling

Example To find the size of the file#include<fstream.h>#include<process.h>Void main(){Ifstream ifil(“abc.txt”);If(!ifill){Cout<<“file cannot open correctly”;exit(-1);}

Page 41: Data File Handling

ifill.seekg(0,ios::end);

int x=ifil.tellg();

Cout<<“size of file is”<<x;

}