0% found this document useful (0 votes)
66 views13 pages

C++010 (Working With Files) A

1. The document discusses file input/output in C++ programs. Files allow storing data externally on storage devices like hard disks. 2. C++ uses file stream classes like ifstream, ofstream and fstream for file I/O. ifstream handles input, ofstream handles output, and fstream handles both. 3. To use a file, a program must open it using the constructor or open() member function of the appropriate file stream class. Opening modes like ios::in and ios::out determine read/write access.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
66 views13 pages

C++010 (Working With Files) A

1. The document discusses file input/output in C++ programs. Files allow storing data externally on storage devices like hard disks. 2. C++ uses file stream classes like ifstream, ofstream and fstream for file I/O. ifstream handles input, ofstream handles output, and fstream handles both. 3. To use a file, a program must open it using the constructor or open() member function of the appropriate file stream class. Opening modes like ios::in and ios::out determine read/write access.
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 13

UNIT-10 Working with files

Write Data ( to file )

External memory DATA files

Read Data (From file)

Program- File Interaction

Internal memory / Program cin>> ( Get data from Keyboard) cout<< (Put data to Screen )

Console Program Ineraction

Console unit (Screen + Keyboard)

A program involves two types of communication: 1. Data transfer between the console unit and the program. 2. Data transfer between the program and disk File. In Normal programming data is stored in main or primary memory. So after the completion of the execution of program, the inputted data will be destroyed. Each time when you executing the program, you have to input data again - and again. This will become a very tedious job if the input data size is very large. Sometimes we need to store our data on secondary storage device like floppy, Hard disk etc. Data storage on such devices uses the concept of files. A file is a collection of related data stored in a particular area on the disk. We can design some programs to perform the read and write operations on these files. The I/O system of C++ handles file operation similar to the console input and output operations. It uses file streams as an interface between the programs and files.

Created By: Deepak Kumar Prajapati B.E. (Information technology) Mob: 9672974917

UNIT-10 Working with files

Input stream: It supplies data to the program. It extracts data from file. Output stream: It receives data from the program. It inserts (write) data to the file.

Read Data

Input Stream
Input data

Disk file
Write data

Program

Output Stream

Data output

Classes for file stream operations The I/O system of C++ uses a set of classes that defines the file handling operation. For file operations it uses classes ifstream, ofstream and fstream. All these classes derived from class fstreambase and corresponding iostream class. We must include file fstream in any program that uses files.

Created By: Deepak Kumar Prajapati B.E. (Information technology) Mob: 9672974917

UNIT-10 Working with files


Stream classes for file operations
ios

istream

streambuf

ostream

iostream file
iostream

ifstream

fstream

ofstream

filebuf

fstream file

fstreambase

Class filebuf

Contents It sets the file buffers to read and write. It contains open( ) and close( ) as member. fstreambase Provides operations common to the file stream. Serves as a base for fstream, ifstream, ofstream class. Contains open( ) and close( ) function. ifstream Provides input operations. Contains open with default input mode. Inherits the functions get( ), getline( ), seekg( ) and tellg( ) functions from istream. ofstream Provides output operations. Contains open( ) with default output mode. Inherits the functions put( ), seekp( ), tellp( ) and write( ) from ostream. fstream Provide support for simultaneous input and output operations. Contains open( ) with default input mode. Inherits all the functions from istream and ostream classes through iostream.
Created By: Deepak Kumar Prajapati B.E. (Information technology) Mob: 9672974917

UNIT-10 Working with files Opening and closing a file


When we want to use a file, we have to decide the following things about the file: 1. Suitable name of the file: Input.data, Test.doc. 2. Data type and structure 3. Purpose 4. Opening method. We can open a file in two ways: 1. Using the constructor function of the class. This method is useful when we use only one file in the stream.

2. Using the member function open( ) of the class.


This method is used when we want to manage multiple files using one stream. 1. Using Constructor: As we know constructor is used to initialize object while it is being created. Here we use file name to initialize file stream object. Two step method: 1) Create a file stream object to manage the stream while it is being created. 2) Initialize the file object with the desired filename. Example: ofstream outfile(Result); Here we are creating an output stream with object name outfile. This stream object is initialized with File name Result. ifstream infile(Data); Here we are creating an input stream with object name infile. This stream object is initialized with File name Data.

The connection with the file closed automatically when the stream object

expires (when the program terminates). Sometimes we need to open a file for both input and output purpose. So instead of using two programs for each purpose we a use a single program that can open the same file for both input and output but one by one.
Created By: Deepak Kumar Prajapati B.E. (Information technology) Mob: 9672974917

UNIT-10 Working with files That means first open the file for input using input stream. After reading close
it and open the same file for output using output stream. Example: Creating file using constructor function
#include<iostream.h> #include<fstream.h> void main() { ofstream outfile(D:\\student.doc); //connect file ITEM to output stream cout<<\nEnter item name: ; char name[30]; cin>>name; cout<<\nEnter roll no. ; int rn; cin>>rn; outfile<<name<<\t<<rn<<\n; outfile.close( ); ifstream infile(D:\\student.doc); infile >> name; infile >> rn; cout<<name<<\t<<rn; infile.close( ); }

//Write data to file //Closing output stream. //Connect file ITEM to input stream //Extract data from file

//Write data to screen //Closing input stream

2. Opening file using open( )


The function open( ) is used to open multiple files that uses the same stream object. Syntax: file-stream-class stream-object; stream-Object.open(student); Example: ofstream outfile; outfile.open(student);

Created By: Deepak Kumar Prajapati B.E. (Information technology) Mob: 9672974917

UNIT-10 Working with files


1. We can open multiple file using single stream object, but one file should be closed before opening other file. Example: ofstream outfile; outfile.open(Student); .. . outfile.close( ); ofstream outfile; outfile.open(Result); .. . outfile.close( ); Program:
#include<iostream.h> #include<fstream.h> #include<conio.h> #include<iomanip.h> void main() { ofstream fout; clrscr(); fout.open("D:\\country.doc"); fout<<"United states of America"; fout<<"India"; fout<<"Austrelia"; fout.close(); fout.open("D:\\Capital.doc"); fout<<"Washington"; fout<<"Delhi"; fout<<"Kenbara"; fout.close(); const int N=80; char line[N]; ifstream fin; fin.open("D:\\country.doc"); cout<<"\nContents of country file\n\n"; while(fin) { fin.getline(line,N); cout<<line; } fin.close(); fin.open("D:\\Capital.doc"); cout<<"\nContents of Capital file\n\n"; while(fin) { fin.getline(line,N); cout<<line; } fin.close(); getch();
Created By: Deepak Kumar Prajapati B.E. (Information technology) Mob: 9672974917

//Creating output stream //Connect stream to file Student

//Disconnect output stream from file Student //Creating output stream //Connect stream to file Result

//Disconnect output stream from file Result

UNIT-10 Working with files


}

2. We can also open two different file in different streams

Disk

connect one file to fout


fout Program

Student

Result Connect one file to fin Fig: Stream working on multiple files

fin

Program

Detecting End of File


Detection of end of file condition is necessary for attempting any further attempts to read data from the file. We can detect End-of-file using two conditions: 1. while(fin) //fin is the object of ifstream fin returns a value 0 if any error occurs in file operation including the end-offile condition. So While loop terminates when fin return a value of zero on reaching the end-of-file condition.

2. if( fin.eof( )!=0 )


{ exit(1); } eof( ) is a member function of ios class. It returns a non-zero value if the endof-file(EOF) condition is encountered, and a 0 otherwise.

Created By: Deepak Kumar Prajapati B.E. (Information technology) Mob: 9672974917

UNIT-10 Working with files File Modes


When we open a file a default opening mode is assign to the file according to type of stream. ofstream fout(Data); //Default opening mode is write mode ifstream fin(Data); //Default opening mode is Read mode We can give opening mode to a file according to our choice/Purpose. Here mode specifies the purpose for which the file is opened. Syntax: stream_objet.open(file_name, mode); mode ios::app ios::ate ios::binary ios::in ios::nocreate ios::noreplace ios::out ios::trunc meaning append to end-of-file Go to end-of-file on opening Binary file Open file for reading only Open fails if the file does not exists. Open fails if the file already exists. Open file for writing only Delete the content of file if it exists.

1. ios::out and ios::trunc both are similar. These modes are used to open a
file for writing only. In this mode if the file with given file-name does not exist then a new file is creates. But if the file is already exist all the contents of this file are removed. 2. ios::noreplace If file is already created then no replacement of new file with old file. 3. ios::binary opens file in binary mode only. 4. ios::in Opens file for reading only if file does not exists then new file is created with given file name. 5. ios::nocreate Same as ios::in but if the given file does not exists then it does not create new file 6. ios::app and ios::ate both functions works same. Their function is to open file for appending / modification. But here is only one difference that ios::app mode permits us to add data to the end of file only. ios::ate mode permits us to add data or to modify the existing data anywhere in the file. 7. We can combine two or more mode parameter using the bitwise OR operator.
Created By: Deepak Kumar Prajapati B.E. (Information technology) Mob: 9672974917

UNIT-10 Working with files


Example: fout.open(Data, ios::app | ios::nocreate); FILE POINTER AND THEIR MANIPULATOR Each file has two associated pointers Input pointer (get pointer) Output pointer (put pointer) These file pointers are used when a file is opened in either read mode or writing mode. We can move these pointers through the file while reading or writing. Input pointer is used for reading the content of given file. Output pointer is used for writing data to a given file location. Default action of pointer Open for reading only Hello file H E L L O input pointer Open in append mode H Open for writing only output pointer E L L O W O R L D output pointer W O R L D

Functions for manipulating file pointer


We can move a file pointer to any desired position inside the file. To control the movement of the file pointer C++ file stream classes supports following functions:

seekg( ) seekp( ) tellg( ) tellp( )

moves get pointer (input) to a specified location. moves put pointer (output) to a specified location. gives the current position of the get pointer. gives the current position of the put pointer.

Created By: Deepak Kumar Prajapati B.E. (Information technology) Mob: 9672974917

UNIT-10 Working with files

syntax: seekg(offset, refposition); seekp(offset, refposition); offset represent the number of bytes the file pointer to be moved to the from the location specified by the parameter refposition. offset(required) refposition(Optional) value may be (-m0+m)

ios::beg start of the file ios::cur current position of the pointer ios::end End of file If you do not this parameter then C++ uses the default parameter according to file open mode. Example: ifstream infile; infile.seekg(10); It moves the file pointer to the byte number 10, But in a file byte number starts from 0. So when we moves file pointer to 10th byte that means we are moving file pointer to the 11th byte of file. seek call fout.seekg(0,ios::beg) fout.seekg(0,ios::cur) fout.seekg(0,ios::end) fout.seekg(m,ios::beg) fout.seekg(m,ios::cur) fout.seekg(m,ios::end) fout.seekg(-m,ios::beg) fout.seekg(-m,ios::cur) fout.seekg(-m,ios::end) Action Go to start. Start at the current position. Go to the end of file. Moves to (m+1)th byte in the file Moves forward by m byte from the current position Not possible Not possible Moves backward by m byte from the current position. Moves backward by m byte from the end.

fout.open(Student, ios::app); int p = fout.tellp( );


Created By: Deepak Kumar Prajapati B.E. (Information technology) Mob: 9672974917

10

UNIT-10 Working with files Sequential input and output operation


C++ supports a number of member functions for input and output operations: Single character input and output: get( ) Reads a single character from the associated stream. put( ) Write a single character to the associated stream. Example: ifstream fin; char c; while(fin) { c = fin.get( ) ; cout<<c; }

OR

fin.get(c);

write( ) and read( ) functions


write( ) and read( ) functions handles data in binary format. That means the values are stored in the disk file in the same format in which they are stored in the internal memory. The binary format is more accurate for storing the numbers as they are stored in the exact internal representation. Syntax: infile. read((char *) &V, sizeof(V)); outfile. write((char *) &V, sizeof(V)); These functions take two arguments. Address of the variables V. It must be cast to type char* Length of the variable in bytes.

Created By: Deepak Kumar Prajapati B.E. (Information technology) Mob: 9672974917

11

UNIT-10 Working with files Reading and writing a class object


The I/O system of C language cannot handle user defined data types such as class object. But class and objects are the central element of C++ programming , so C+ + has binary input and output function read( ) and write( ) for this purpose. These functions can handle entire structure of an object as a single unit. Function write( ) copies a class object from memory, byte to byte with no conversion. Example:
#include<iostream.h> #include<fstream.h> #include<conio.h> #include<iomanip.h> class student { char name[30]; int rn; char br[10]; public: void readdata( ); void writedata( ); }; void student::readdata() { cout<<"\nEnter name: "; cin>>name; cout<<"\nRoll no.: "; cin>>rn; cout<<"\nEnter Branch: "; cin>>br; } void student::writedata() { cout<<setiosflags(ios::left)<<setw(10)<<name<<setiosflags(ios::right)<<setw(10)<<rn <<setw(10)<<br<<endl; } void main( ) { student st[3]; fstream file; file.open("D:\\student.doc",ios::in | ios::out); cout<<"\nEnter details for three students\n"; for(int i=0;i<3;i++) { st[i].readdata(); file.write((char *) & st[i],sizeof(st[i])); } file.seekg(0); cout<<"\nOutput\n\n"; for(i=0;i<3;i++) { file.write((char *) & st[i],sizeof(st[i])); st[i].writedata(); } }
Created By: Deepak Kumar Prajapati B.E. (Information technology) Mob: 9672974917

12

UNIT-10 Working with files Updating a file: Random access


When you are maintaining a file, You need following task: 1) Displaying the content of a file 2) Modifying existing item 3) Adding a new item. 4) Deleting an existing item To applying these actions we have to move file pointer to a particular location, that corresponds to the item/object under consideration. This can be easily implemented, if the file contains a collection of item/objects of equal lengths. Size of an object int length = sizeof(object); Location of the desired object int location = m * length; //m = size of data type

This location gives us the byte number of the first byte of the mth object. Now we can set the file pointer to reach this byte with the help of seekg( ) or seekp( ). Total no. of objects in a file int n = file_size / object_length; file_size = Using tellg( ) or tellp( ) when the file pointer is located at the end of the file. Example:

Created By: Deepak Kumar Prajapati B.E. (Information technology) Mob: 9672974917

13

You might also like