Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Files in c++

2,662 views

Published on

It is mainly for beginners...

Published in: Education
  • how to use file in c++ with stack?
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here

Files in c++

  1. 1. Prepared by : SELVIN JOSY BAI.S
  2. 2.  Use of header file fstream.h Types of stream objects open() and close() functions File mode constants Reading and writing characters from / todisk Detecting end of file Reading and writing objects from / to disk File pointers for Random Access Error handling functions
  3. 3. Most computer programs work with files.Word processors create document files.Database programs create files of information.Compilers read source files and generate executablefiles.In C++, file input / output facilities are implementedthrough a component header file of C++ standardlibrary. This header file is fstream.h.
  4. 4. File Stream Read dataA File stream act as aninterface between theprogram and the files.•The stream thatsupplies data to theprogram is known asinput stream.•The stream thatreceives data from theprogram is known asoutput stream.DiskFilesProgramData inputWrite dataDataoutputOutput streamInput stream
  5. 5. CLASSES FOR FILE STREAM OPERATIONSiosistream streambuf ostreamiostreamifstream fstream ofstream filebuffstreambase…………………………………………………………………………………………………………………………………………….iostreamfilefstreamfile
  6. 6. Using fstream.hA stream is a sequence of bytes.It is a general name given to a flow of data.Different streams are used to representdifferent kinds of data flow.ifstream class represents input disk files.ofstream class represents output disk files.fstream – for both input and outputMember functions of these classes are used toperform I/O operations.
  7. 7. Different Classes and its functionsClass Functionsfilebuf It sets the file buffers to read and write.Member functions : open(), close()fstreambase This is the base class for fstream, ifstream andofstream classes.Member functions : all input and output functions,open(), close()ifstream It provides input operations for file.Member functions : get(), getline(), read(),seekg(), tellg()ofstream It provides output operations for file.Member functions : put(), write(), seekp(), tellp()fstream It is an input-output stream class
  8. 8. Opening and closing filesIn C++, if we want to open a file, we must first obtain astream.(objects)Opening of files can be achieved in two ways:1. using the constructor function of the stream classsyntax : stream streamobject(“name of filename”);2. using the function Open( )Syntax : stream streamobject;streamobject.open(“name of filename”);A file is closed by disconnecting it with the stream it isassociated with.Syntax : streamobject.close()
  9. 9. Types of FilesFiles are of two types.1. ASCII file or Text File :Those files created by storingcharacters2. Binary file :Those files created by storing ablock of memory
  10. 10. The concept of file modes:It describes how a file is to be used•to read from it•to write to it•to append it•to read and write and so on.Syntax :streamobject.open( “filename”, file-mode);
  11. 11. File mode constantsSl.No File modes MeaningStreamtype1 ios :: in it opens file for reading ifstream2 ios :: out it opens file for writing ofstream3 ios :: appIt causes all output to that file to beappended to the endofstream4 ios :: ateIt seeks to end-of-file upon opening of thefile.ofstream5 ios :: trunc Delete contents of the file if it exists ofstream6 ios :: nocreateIt causes the open() functions to fail if thefile does not already exist. It will not createa new file with that name.ofstream7 ios :: noreplaceIt causes the open() functions to fail if thefile already exist. This is used when wewant to create a new file and at the sametimeifstream8 ios :: binaryIt causes a file to be opened in binarymode.ifstream,ofstream
  12. 12. Reading and writing charactersfrom / to diskThe functions put() and get() are usedfor manipulating a file character bycharacter.These functions are members of ostreamand istream respectively.put() is used for output to the file.get() is used for input from file.
  13. 13. To create a File using put()#include<fstream.h>void main(){ofstream outfile(“out.txt”);char str[]=“This is a text file”;int i=0;while(str[i])outfile.put(str[i++]);outfile.close();}
  14. 14. To read a File using get()#include<fstream.h>void main(){ char ch;ifstream infile(“out.txt”);while(infile){ infile.get(ch);cout << ch;}infile.close();}
  15. 15. Detecting End of File(eof())eof() is a member of ios class.It returns a non-zero value if the end-of-file is encountered and a zerootherwise.
  16. 16. Reading and writing class objectsfrom / to diskThe functions write() and read() areusually used to transfer a block of datafrom and to the file.These functions are members ofofstream and ifstream respectively.write() is used for output to the file.read() is used for input from file.
  17. 17. write() functionTo write to the fileIt takes two argumentsi.e., a pointer to the block andthe size of the blockEg.,stdfile.write((char *)&s, sizeof(student));
  18. 18. read() functionTo get the contents from the fileIt takes two argumentsi.e., a pointer to the block andthe size of the blockEg.,stdfile.read((char *)&s, sizeof(student));
  19. 19. Program to Create a student File#include <fstream.h>class student{private :int regno, mark;char name[20];public:void getdata();};
  20. 20. void student :: getdata(){cout << “nEnter reg. number: “;cin >> regno;cout << “nEnter Name of Student:”;gets(name);cout << “nEnter Marks:”;cin >> marks;}
  21. 21. void main(){ student ob;fstream stdfile;stdfile.open(“stud.dat”,ios::out);char flag;do{ ob.getdata();stdfile.write((char *)&ob,sizeof(student));cout << “n Continue ? y/n”;cin >> flag;} while(flag==‘Y’ || flag==‘y’);stdfile.close();}
  22. 22. Program to Display a student File#include <fstream.h>class student{private :int regno, mark;char name[20];public:void getdata();void display();};
  23. 23. void student :: getdata(){cout << “nEnter reg. number: “;cin >> regno;cout << “nEnter Name of Student:”;gets(name);cout << “nEnter Marks:”;cin >> marks;}
  24. 24. void student :: display(){cout << “nRegister number: “ <<regno;cout << “nName of Student:”<<name;cout << “nMarks:” <<marks;}
  25. 25. void main(){ student ob;fstream stdfile;stdfile.open(“stud.dat”,ios::in);stdfile.read((char *)&ob,sizeof(student));while(stdfile){ob.display();stdfile.read((char *)&ob,sizeof(student));}stdfile.close();}
  26. 26. Open for READING only H A IInput pointerOpen for WRITING onlyoutput pointerOpen for APPEND mode H A Ioutput pointer
  27. 27. File Pointers for Random AccessWhen we open a file in more than one mode usingthe fstream class, it is not necessary to close the fileand open it again when we need to switch from onemode to another.But if we are writing and reading in different indifferent positions of the file, then, the streampointers have to be positioned appropriately.Each file object is associated with two integer valuescalled the get_pointer and the put_pointer. Theseare also called the current postion. These valuesspecify the byte number in the file.
  28. 28. Functions to move the File Pointerseekg() Moves get_pointer(inputpointer) to a specified location.seekp() Moves put_pointer(outputpointer) to a specified location.tellg() Gives the current position to theget_pointertellp() Gives the current position to theput_pointer
  29. 29. Example:infile.seekg(15);It moves the file pointer to the byte number 15.It is to be remembered that the bytes in a fileare numbered beginning from zero. Therefore,the file pointer will be pointing to the 16th bytein the file
  30. 30. Example:ofstream ofile;ofile.open(“employee”,ios::app);int ptr = ofile.tellp();On execution of these statements, the outputpointer will be moved to the end of the file“employee” and the value of ptr will representthe number of bytes in the file.
  31. 31. seekg() and seekp() functions It takes one or two arguments. If it takes two arguments, thenthe first one is the relative offset, ie., thenumber of bytes the file pointer has to be moved(+ for forward and – for backward)The second argument is the position of the filepointer from where the offset is to be considered. The default argument for this is the beg It can take values ios::beg, ios::end, ios::cur
  32. 32. Error Handling functionsThe different possible error situations areenumerated below The file name used for a new file may be anexisting file name A file which we are attempting to open for readingmay not exist. There may be no more room on the disk for storingthe newly created file. We may attempt to perform an operation when thefile is not opened for that purpose.
  33. 33. Error Handling Functionseof() Returns non-zero if the end of file isencountered while reading. Otherwisereturns zero.fail() Returns non-zero when an input oroutput operation has failed.bad() Returns non-zero values if an invalidoperation is attempted or anyunrecoverable error has occurred.However, if it is zero it may be possible torecover from any other error reportedand continue operation
  34. 34. Error Handling Functionsgood() Returns non-zero values if no errorhas occurred. When it returns zero, nofurther operations can be carried out.clear() Resets the error state so that furtheroperations can be attempted

×