Working with files A File is a collection

  • Slides: 24
Download presentation
Working with files • A File is a collection of related data stored in

Working with files • A File is a collection of related data stored in a particular area on the disk. • Programs can be designed to perform read and write operations on these files.

File input and output streams Disk Files

File input and output streams Disk Files

Classes for File Stream operations • All the below classes are derived from fstream

Classes for File Stream operations • All the below classes are derived from fstream base and from corresponding iostream class. • These classes are designed to manage the disk files, are declared in fstream base Ifstream ofstream filebuf

 • • Details of file stream classes Filebuf- used to set the file

• • Details of file stream classes Filebuf- used to set the file buffers to read and write. It contains open( ) and close( ). Fstreambase- serves as a base for fstream, ifstream and ofstream. Contains open( ) and close( ). Ifstream-provides input operations. Contains open( ) with input mode. Inherits the functions get(), getline(), read(), seekg()and tellg() from istream. Ofstream-provides output operations. Contains open( ) with output mode.

 • Inherits put(), seekp(), tellp() and write() from ostream. • Ftream- provides support

• Inherits put(), seekp(), tellp() and write() from ostream. • Ftream- provides support for input and output operations. Contains open( ) with input mode. Inherits all the functions from istream and ostream through iostream.

Opening and Closing a file • If we want to use a disk file,

Opening and Closing a file • If we want to use a disk file, we need to decide the following things about the file and its intended use. 1. Suitable name for the file 2. Data type and structure 3. Purpose and 4. Opening method

 • In formatted I/O, numbers are stored on disk as a series of

• In formatted I/O, numbers are stored on disk as a series of characters. • If you want to store 6. 02; will be stored as 4 byte float or as an 8 byte type double as characters ‘ 6’, ‘ 0’ and ‘ 2’. • Note: ofstream class contains an object called outfile and ifstream contains infile. • When the program terminates , the outfile object goes out of the scope. This calls the destructor, which closes the file, so we dont need to close the file explicitly.

 • For opening a file, we must create a file stream and then

• For opening a file, we must create a file stream and then link it to the filename. • A file stream can be defined using the classes ifstream, ofstream and fstream that are contained in header file fstream. • The class to be used depends upon the purpose, that is, whether we want to read data from a file or write data to a file. • A file can be opened in two ways: 1. Using the constructor function of the class. 2. Using the member function open( ) of the class.

 • The filename is a string of characters that make up a valid

• The filename is a string of characters that make up a valid filename for the operating system. • It contains two parts: a primary name an optional period with extension. Examples: input. data test. doc student data. txt

Writing data to a file #include<iostream. h> #include<fstream. h> Int main( ) { char

Writing data to a file #include<iostream. h> #include<fstream. h> Int main( ) { char ch=‘x’; int j=77; double d=6. 02; string str 1=“apple”; //String without string str 2=“banana”; //embedded spaces. ofstream outfile(“fdata. txt”); //creates ofstream object outfile<<ch<<j<<‘ ‘<<d<<str 1<<‘ ‘<<str 2<<endl; cout<<“File is written successfully n”; return 0; }

Output stream outfile DISK Results File Program Input stream infile Data file

Output stream outfile DISK Results File Program Input stream infile Data file

 • Ofstream outfile(“results”); //output only • Ifstream infile(“data”); //input only Ex: outfile<<“TOTAL”; outfile<<sum;

• Ofstream outfile(“results”); //output only • Ifstream infile(“data”); //input only Ex: outfile<<“TOTAL”; outfile<<sum; infile>>number; infile>>string; Note: outfile. close( ); // this statement disconnects the file from the output stream outfile.

Opening files using open( ) • The function open( ) can be used to

Opening files using open( ) • The function open( ) can be used to open multiple files. • If you want to process a set of files sequentially; create a single stream object and use it to open each file. File-stream class stream object; Stream-object. open (“filename”); Ex: ofstream outfile; //creating stream for output outfile. open(“DATA 1”); //connect stream to DATA 1 ---------------outfile. close( ); //disconnect stream from DATA 1 outfile. open (“DATA 2”); //Connect stream to DATA 2 -------------------------------------outfile. close( ); //disconnect stream from DATA 2

Reading the data • We can read the file by using an ifstream object,

Reading the data • We can read the file by using an ifstream object, initialized to the name of the file. • The file is automatically opened when the object is created. We can then read from it using the extraction(>>) operator.

#include<fstream. h> #include<iostream. h> #include<string. h> int main( ) { char ch; int j;

#include<fstream. h> #include<iostream. h> #include<string. h> int main( ) { char ch; int j; doublche d; string str 1; string str 2; ifstream infile(“fdata. txt”); //create ifstream object extracts (read) data from it. infile>>ch>>j>>d>>str 1>>str 2; cout<<ch<<j<<d<<str 1<<str 2<<endl; return 0; } that

Character I/O • The put( ) and get( ) functions, which are the members

Character I/O • The put( ) and get( ) functions, which are the members of ostream and istream, respectively, can be used to output and input the single characters. • In a program, the length of the string can be found using a member function called size( ).

Writing a Character #include<fstream. h> #include<iostream. h> #include<string. h> int main( ) { string

Writing a Character #include<fstream. h> #include<iostream. h> #include<string. h> int main( ) { string str=“KL University”; ofstream outfile(“TEST. TXT”); //creates file for output for(int j=0; j<str. size( ); j++) outfile. put(str[j]); cout<<“File is written succesfully”; return 0; }

Reading a Character int main( ) { Char ch; Ifstream infile(“test. txt”); While(infile) //read

Reading a Character int main( ) { Char ch; Ifstream infile(“test. txt”); While(infile) //read until eof or error { infile. get(ch); cout<<ch; } Cout<<endl; return 0; }

File Modes Stream-object. open(“filename”, mode); Ios: : app Append to end-of-file Ios: : ate

File Modes Stream-object. open(“filename”, mode); Ios: : app Append to end-of-file Ios: : ate Go to end of file on opening Ios: : binary Binary file Ios: : in open file for reading only Ios: : nocreate open files if the file does not exist Ios: : noreplace open files if the file already exits Ios: : out open the file for writing only Ios: : trunc delete the contents of the file.

Binary I/O File Write a Program that shows how an array of integers is

Binary I/O File Write a Program that shows how an array of integers is written to disk and then read back into memory using binary format. #include<fstream. h> int buff[max] int main( ) { for(int j=0; j<max; j++) buff[j]=j; ofstream os(“edata. dat”, ios: : binary)

Os. write(reinterpret. cast<char*>(buff), max*size(int); Os. close( ); for(j=0; j<max; j++) buff[j]=0; //erase buffer Ifstream

Os. write(reinterpret. cast<char*>(buff), max*size(int); Os. close( ); for(j=0; j<max; j++) buff[j]=0; //erase buffer Ifstream is(“edata. dat”, ios: : binary); Is. read(reinterpret_cast<char*>(buff), max*size(int); for(j=0; j<max; j++) if(buff[j]!=j) cout<<“data in correct n”; return 0

Writing an object to disk Class person { protected: char name[20]; int age; public:

Writing an object to disk Class person { protected: char name[20]; int age; public: void getdata() { cout<<“enter name”; cin>>name; cout<<“enter age”; cin>>age; } };

int main() { person p; p. getdata(); ofstream outfile(“person. dat”, ios: : binary) outfile.

int main() { person p; p. getdata(); ofstream outfile(“person. dat”, ios: : binary) outfile. write(reintepret_cast<char*>(&p), sizeof(p)); return 0; }

Reading object from disk Infile. read(reinterpret_cast<char*>(&p), sizeof(p)); p. showdata( ); return 0;

Reading object from disk Infile. read(reinterpret_cast<char*>(&p), sizeof(p)); p. showdata( ); return 0;