Publicidad

Data file handling in c++

27 de Aug de 2016
Publicidad

Más contenido relacionado

Publicidad
Publicidad

Data file handling in c++

  1. DATA FILE HANDLING IN C++
  2. What if a FILE? A file is a stream of bytes stored on some secondary storage devices.
  3. NEED FOR DATA FILES  Many real life problems requires handling of large amount of data.  Earlier we used arrays to store bulk data.  The problem with the arrays is that arrays are stored in RAM.  The data stored in arrays is retained as long as the program is running. Once the program is over the data stored in the arrays is also lost.  To store the data permanently we need files. Files are required to save our data (on a secondary storage device) for future use, as RAM is not able to hold our data permanently.
  4. Difference between Files and Arrays( graduating to files ): DIFFERENCE BETWEEN ARRAYS AND FILES ARRAYS FILES Arrays are stored in RAM Files are stored on Hard Disk Data is stored temporarily Data is stored permanently Arrays have fixed size File can have variable size Arrays can not be used to share data between programs. Files can be used to share data between programs.
  5. INPUT/OUTPUT IN C++ STREAMS  The input/output system of C++ handles file I/O operations in the same way it handles console I/O operations.  It uses file stream as an interface between programs and files.  A stream is defined as the flow of data.  Different kinds of stream are used to represent different kinds of data flow.  Output stream: The stream which controls the flow of data from the program to file is called output stream.  Input stream: The stream which controls the flow of data from the file to the program is called input stream. Input Stream Output Stream Disk File C++ Program Read data Extract from input stream Insert into output stream Write data
  6. INPUT/OUTPUT IN C++ CLASSES Each stream is associated with a particular class which contains definitions and methods for dealing with that particular kind of data These include fstream, ifstream and ofstream. These classes are defined in the header file fstream.h. Therefore it is necessary to include this header file while writing file programs. The classes contained in fstream.h are derived from iostream.h. Thus it is not necessary to include iostream.h in our program, if we are using the header file fstream.h in it. IOS IOSTREAM FSTREAM ISTREAM get () getline() read() >> OSTREAM put () write() << IFSTREAM seekg() tellg() open() >> OFSTREAM seekp() tellp() open() <<
  7. INPUT/OUTPUT IN C++ CLASSES contd…. The ifstream class contains open() function with default input mode and inherits the functions get(), getline(), read(), seekg() and tellg(). The ofstream class contains open() function with default output mode and inherits functions put(), write(), seekp() and tellp() from ostream. The fstream class contains open() function with default input/output mode and inherits all I/O functions from iostream.h.
  8. TYPES OF DATA FILES There are two types of data files in C++: Text files and Binary files  Text files store the information in ASCII characters. Each line of text in text files is terminated by a special character called EOL. In text files some internal translations take place while storing data.  Binary files store information in binary format. There is no EOL character in binary files and no character translation takes place in binary files.
  9. DIFFERENCE BETWEEN TEXT FILES AND BINARY FILES These differ on six main parameters: TEXT FILES BINARY FILES Handling of new lines In text files various character translations are performed such as “r+f”(carriage return- linefeed combination)is converted into “n”(new line) while reading from a file and vice-versa while writing. In binary files no such translations are performed. Portability Portable: one can easily transfer text file from one computer to the other Non portable: Binary files are dependent. If the new computer uses a different internal representation for values they cannot be transferred. Storage of numbers In text files when we store numbers they are stored as characters eg if we store a decimal no 42.9876 in a text file it occupies 7 bytes In a binary file 42.9876 is stored in 4 bytes
  10. Text Files Binary Files Readability Are readable and thus can be easily edited using any word editor. Not readable Storage Occupy more space due to character conversions Occupy less space. Accuracy While reading/writing of numbers, some conversion errors may occur. Highly accurate for numbers because it stores the exact internal representation of values. DIFFERENCE BETWEEN TEXT FILES AND BINARY FILES contd…
  11. OPENING FILES Opening of files can be achieved in two ways:  Using Constructor function: This method is useful when we open only one file in a stream. To open a file using a constructor fuction we create an object of desired stream and initialize that object ith the desired file name. For eg. The statement ofstream fout(“ABC.TXT”); will create an onject fout of class ofstream, opens the file ABC.TXT and attaches it to the output stream for writing. Similarly the statement ifstream fin(“ABC.TXT); will create an object fin of class ifstream, opens the file “ABC.TXT” and attaches it to the input stream for reading.  Using open() function: This method is useful when we want to open multiple files using a single stream. For eg. ifstream fin; //creates input stream fin.open(“ABC.TXT”); // associates ABC.TXT to this stream fin.close(); // closes the file fin.open(“XYZ.TXT”); // associates the input stream with file XYZ.TXT
  12. CLOSING FILES The connections with a file are automatically closed when the input and output stream objects expires ie when they go out of scope. However we can close the file explicitly by using the close() method: fin.close(); Closing a file flushes the buffer which means the data remaining in the buffer of input/output stream is moved to its appropriate place. For example, when an input files connection is closed, the data is moved from the input bufferto the program and when an output file connection is closed the data is moved from the output buffer to the disk file.
  13. FILE MODES File modes describes the way in which a file is to be used. The most common file modes are : File Modes Exolanation ios::in Opens file for reading. File pointer is at the beginning of the file ios::out Opens file for writing. If the file is already created and opened in this mode all the previous content gets erased from the file. ios::app Opens file for adding new records. File pointer is at the end of the file. New records can be added only at the end of the file. ios::ate Opens the file for both reading and writing. File pointer is at the end of the file when file is opened in his mode but can be moved to any location in the file using file pointer methods. ios::binary Opens file in binary mode. By default the file is opened n text mode. Two or more modes can be combined using the bitwise operator |
  14. TEXT FILE FUNCTIONS  Reading/writing a single character from/to file : get() – read a single character from text file and store in a buffer. e.g file.get(ch); put() - writing a single character in text file. e.g. file.put(ch);  Reading/writing a line from/to file: getline() - read a line of text from text file stored in a buffer. e.g file.getline(s,80,”n”); <<(insertion operator) – write a line to a file. fin<<s;  Reading/writing a word from/to file: char ch[20]; fin.getline(ch,20, ‘ ‘); We can use file>>ch for reading and file<<ch writing a word in text file. The >> operator does not accept white spaces so it will stop when it encounters a space after word and stores that word in ch.
  15. A PROGRAM TO CREATE A TEXT FILE #include<fstream.h> void main() { ofstream fout(“abc.txt”); fout<<“ i am creating a new text filen”; fout<<“this text file contains alphabets and numbersn”; fout.close(); } The above program will create a text file “abc.txt” and store two lines in it. You can store as many lines as you want.
  16. #include<fstream.h> void main() { ifstream fin(“abc.txt”); char ch; while(!fin.eof()) { fin.get(ch); cout<<ch; } fin.close(); } A PROGRAM TO READ A TEXT FILE CHRACTER BY CHARACTER The above program will read a text file “abc.txt” one character at a time and display it on the screen.
  17. #include<fstream.h> void main() { ifstream fin(“abc.txt”); char ch[20]; while(!fin.eof()) { fin>>ch; cout<<ch; } fin.close(); } A PROGRAM TO READ A TEXT FILE WORD BY WORD The above program will read a text file “abc.txt” one word at a time and display it on the screen.
  18. #include<fstream.h> void main() { ifstream fin(“abc.txt”); char ch[80]; while(!fin.eof()) { fin.getline(ch,80,”n”); cout<<ch; } fin.close(); } A PROGRAM TO READ A TEXT FILE LINE BY LINE The above program will read a text file “abc.txt” one line at a time and display it on the screen.
  19.  read()- read a block of binary data or reads a fixed number of bytes from the specified stream and store in a buffer. e.g file.read((char *)&s, sizeof(s));  write() – write a block of binary data or writes fixed number of bytes from a specific memory location to the specified stream. e.g file.write((char *)&s, sizeof(s)); Note: Both functions take two arguments. • The first is the address of variable, and the second is the length of that variable in bytes. The address of variable must be type cast to type char*(pointer to character type) • The data written to a file using write( ) can only be read accurately using read( ). BINARY FILE FUNCTIONS
  20. #include<fstream.h> class student { private: int rollno; float total; public: void indata() { cin>>rollno>>total;} void outdata() {cout<<rollno<<total;} } A PROGRAM TO CREATE A BINARY FILE The above program will create a binary file “xyz.dat” and store n records in it. void main() { ofstream fout(“xyz.dat”, ios::binary); student stu; int n, i=0; cout<<“enter no of records you want to add to a file”; cin>>n; while(i<n) {stu.indata(); fout.write((char*)&stu, sizeof stu); i++; } fout.close(); }
  21. #include<fstream.h> #include<process.h> class student { private: int rollno; float total; public: void indata() { cin>>rollno>>total;} void outdata() {cout<<rollno<<total;} } A PROGRAM TO READ A BINARY FILE The above program will read the binary file “xyz.dat” and display all records stored in it. void main() { ifstream fin(“xyz.dat”, ios::binary); if(!fin) {cout<<“error in opening file”; exit(-1); } student stu; while(!fin.eof()) { fin.read((char*)&stu, sizeof stu); stu.outdata(); i++; } fin.close(); }
  22. #include<fstream.h> #include<process.h> class student { private: int rollno; float total; public: void indata() { cin>>rollno>>total;} void outdata() {cout<<rollno<<total;} } A PROGRAM TO ADD NEW RECORDS TO BINARY FILE The above program will add n new records at the end of the binary file “xyz.dat”. void main() { ofstream fout(“xyz.dat”, ios::binary| ios::app); student stu; int n, i=0; cout<<“enter no of records you want to add to a file”; cin>>n; while(i<n) {stu.indata(); fout.write((char*)&stu, sizeof stu); i++; } fout.close(); }
  23. #include<fstream.h> #include<process.h> class student { private: int rollno; float total; public: void indata() { cin>>rollno>>total;} void outdata() {cout<<rollno<<total;} Int retroll() { return rollno;} } A PROGRAM TO DELETE A RECORD FROM BINARY FILE The above program will read the binary file “xyz.dat” and write the records into the binary file “def,dat” except the record which we want to delete. Later the old file def.dat is removed and new file def.dat is renamed as xyz.dat. void main() { ifstream fin(“xyz.dat”, ios::binary); ofstream fout(“def.dat”, ios::binary); if(!fin) {cout<<“error in opening file”; exit(-1); } student stu; int roll; cout<<“enter roll no of student whose record you want to delete”; cin>>roll; while(!fin.eof()) { fin.read((char*)&stu, sizeof stu); if (stu.retroll() != roll) {fout.write((char*)&stu, sizeof stu); } } fin.close(); fout.close(); remove(“xyz.dat”); rename(“def.dat”, “xyz.dat”); }
  24. All i/o streams objects have, at least, one internal stream pointer. ifstream, like istream, has a pointer known as the get pointer that points to the element to be read in the next input operation. ofstream, like ostream, has a pointer known as the put pointer that points to the location where the next element has to be written. Finally, fstream, inherits both, the get and the put pointers, from iostream. The default reading pointer is set at the beginning of the file. The default writing pointer is set at the end of the file when the file is opened in app mode. FILE POINTERS
  25. There are two types of file pointers. These are: get pointer – specifies the location in a file where the next read operation will occur. put pointer – specifies the location in a file where the next write operation will occur. In other words, these pointers indicate the current positions for read and write operations, respectively. Each time an input or an output operation takes place, the pointers automatically advance sequentially. It is also possible to read from and write to an arbitrary locations in the file by moving the file pointer. FILE POINTERS contd…
  26. FUNCTIONS ASSOCIATED WITH FILE POINTERS  get pointer: The functions associated with get pointer are seekg() tellg()  put pointer: The functions associated with put pointer are seekp() tellp() The seekg() or the seekp() functions are used to move the get and put pointers respectively either to an absolute address within the file or to certain number of bytes from a particular position. The tellg() and tellp() functions can be used to find out the current position of the get and put file pointers respectively in a file.
  27. seekg()/seekp() FUNCTIONS  The seekg() member function takes two arguments:  Number of bytes to move. (also called offset)  Reference in the file from which the pointer has to be repositioned. There are three reference points defined in the ios class: • ios:beg – the beginning of the file. • ios:cur – the current position of the file pointer. • ios:end – the end of the file.  For eg. ifstream fin(“ABC.TXT”); fin.seekg(10, ios::beg); // here 10 is the offset and ios::beg is the reference position  If the reference point is not specified, ios::beg reference point is assumed. For eg. fin.seekg(50); // here the file pointer is moves ahead 50 bytes from the current position
  28. Command Explanation fin.seekg(0,ios::beg); Moves the file pointer to the beginning of the file fin.seekg(10,ios::beg); Moves the file pointer to 10 bytes from the beginning of the file fin.seekg(10,ios::cur); Moves the file pointer to 10 bytes ahead from the current position of the file fin.seekg(-10,ios::cur); Moves the file pointer to 10 bytes backward from the current position of the file Fin.seekg(0,ios::cur); The file pointer remains at the same position fin.seekg(-10,ios::end); Moves the file pointer to 10 bytes backward from the end of the file fin.seekg(0,ios::end); Moves the file pointer to the end of the file The seekp() function is identical to the seekg() function, but it is identified with the put pointer. seekg()/seekp() FUNCTIONS contd…
  29. tellg()/tellp() FUNCTIONS The tellg() function does not have any arguments. It returns the current byte position of the get pointer relative to the beginning of the file. For example: Ifstream fin(“ABC.TXT”); long pos = fin.tellg(); The above command will assign the current position of the get pointer to the variable pos. The tellp() function is identical to the tellg() function, but it is identified with the put pointer.
  30. #include<fstream.h> #include<process.h> class student { private: int rollno; float total; public: void indata() { cin>>rollno>>total;} void outdata() {cout<<rollno<<total;} } A PROGRAM TO USE FILE POINTERS IN A BINARY FILE The above program will read the binary file “xyz.dat” and modify the record of the desired roll number. void main() { fstream fin(“xyz.dat”, ios::binary | ios::ate); if(!fin) {cout<<“error in opening file”; exit(-1); } student stu; int roll; cout<<“enter roll no of student whose record you want to modify”; cin>>roll; while(!fin.eof()) { fin.read((char*)&stu, sizeof stu); if (stu.retroll() == roll) {cout<<“enter data to be modified”; stu.indata(); fin.seekg(-sizeof(stu), ios::curr); fin.write((char*)&stu, sizeof stu); } fin.close(); }
Publicidad