Presentation is loading. Please wait.

Presentation is loading. Please wait.

C++ FILE I/O.

Similar presentations


Presentation on theme: "C++ FILE I/O."— Presentation transcript:

1 C++ FILE I/O

2 STREAM Files are extremely useful because often the data for a program comes from a file and often the results are stored in a file. Files are usually stored on magnetic disk where they will remain for years even when the power is off. System software of a computer system uses a few other semi-permanent forms of storage, such as the ROM (read-only memory) of the computer and the boot sector of a hard disk. Stream is flow of data Stream in c++ is sequence of character that performs input and output operations In c++ stream is represented as objects of a class Notepad is written to read and write text files. A text file is a file that contains bytes that represent: MS Word files are not text files because the bytes are used to represent many types of information. In addition to characters, byte patterns are used to store formatting and font information. Notepad is not written to deal with this information and will not work correctly with a file that contains it. This is somewhat like a book written in English and a book written in Latin. The same book shelf could hold both books and both books use the same characters printed on paper. But some readers can only process the book written in English.

3 Predefined streams STREAM MEANING Default device Cout
Standard output stream Screen Cin Standard input stream keyboard Cerr Standard error output Ifstream Stream class to read from files(Input) File Ofstream Stream class to write to files (Output) Fstream i/o file Like C, C++ does not have built-in input/output capability. All C++ compilers, however, come bundled with a systematic, object-oriented I/O package, known as the iostream classes. The stream is the central concept of the iostream classes. You can think of a stream object as a smart file that acts as a source and destination for bytes. A stream's characteristics are determined by its class and by customized insertion and extraction operators. Through device drivers, the disk operating system deals with the keyboard, screen, printer, and communication ports as extended files. The iostream classes interact with these extended files. Built-in classes support reading from and writing to memory with syntax identical to that for disk I/O, which makes it easy to derive stream classes.

4 File Input and Output Stream
C++ uses file streams as an interface between the programs and the data files. Input Stream Read Data Data input Disk Files Program Output Stream Write Data Data output

5 File Input and Output Stream
The stream that supplies data to the program is known as input stream Input stream extracts (or read) data from file Input Stream Read Data Data input Disk Files Program Output Stream Write Data Data output The stream that receives data from the program is known as output stream Output stream inserts (or writes) data to the file

6 Classes for file Stream in C++
ofstream – writing to a file ifstream – reading for a file fstream – reading / writing

7 File File can be opened in two ways
For opening a file, we must first create a file stream and then link it to the file using the filename. A file stream can be defined using the classes ifstream, ofstream, and fstream File can be opened in two ways 1)Using the constructor of the class Useful only when there’s one file in the stream 2)Using member functions open() of the class Multiple files using one stream

8 Functions to read and write
Data Functions for reading file Function for writing into file char get(); put(); word >>(extraction operator) << (insertion operator) line getline(); << (insertionoperator) Objects read() write()

9 1)Opening file using constructor
1: To access file handling routines: #include <fstream.h> 2: To declare variables that can be used to access file: ifstream fin; ifstream fin(“infile.dat”); ofstream fout; ofstream fout(“outfile.dat”); This sets up the stream to read data from the file “infile.dat” and write to a file called “outfile.dat” If any error the stream will have an error flag which can be checked by fail() fail() returns true if the last operation failed 4: To see if the file opened successfully: if (fin.fail()) //! fin { cout << "Input file open failed\n"; exit(1); }

10 fin >> num fout << num fin.close(); fout.close();
5.To get data from a file read it using the extraction operator: fin >> num 6: To put data into a file, use insertion operator: fout << num 7: When done with the file: fin.close(); fout.close(); Notifies the OS that file is finished and to flush the buffers and update file security information

11 Example writing strings
Writing to a file int main() { ofstream fout("INVNTRY"); if(!fout) { cout << "Cannot open INVENTORY file.\n"; return 1; } fout << "Radios " << << endl; fout << "Toasters " << << endl; fout << "Mixers " << << endl; fout.close();

12 ifstream fin("INVNTRY"); char item[20]; float cost;
Reading from a file int main() { ifstream fin("INVNTRY"); if(!fin) { cout << "Cannot open INVENTORY file.\n";return1; } char item[20]; float cost; fin >> item >> cost; cout << item << " " << cost << "\n"; fin.close(); }

13 File Modes 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 fails if the file does not exist ios::noreplace  Open files if the file already exists ios::out  Open file for writing only ios::trunc  Delete the contents of the file if it exists

14 More on files&Binary I/O
Default text files Open with file modes ofstream fout("balance", ios::out | ios::binary); ifstream fin("balance", ios::in | ios::binary); Detecting EOF 1)While(fin) { do the processing } 2)If(fin.eof()!=o)

15 Reading and writing character
Writing chars to file int main() { ofstream fout(“charfile", ios::out | ios::binary); if(!fout) {cout << "Cannot open output file.\n"; return 1;} for(int i=0; i<256; i++) fout.put((char) i); } fout.close();

16 Reading and writing characters
int main() { char ch; ifstream fin(“charfile”, ios::in | ios::binary); if(!fin) {cout << "Cannot open file."; return 1;} while(fin) // fin will be false when eof is reached fin.get(ch); cout << ch; }

17 Reading lines of data Int main() { ifstream fin(“ex.txt”); if(!fin) {cout << "Cannot open input file.\n";return 1;} char str[255]; while(fin) { fin.getline(str, 255); // delim defaults to '\n‘ cout << str << endl; } fin.close(); return 0;

18 Ignore function int main() { ifstream fin("test"); if(!fin) { cout << "Cannot open file.\n"; return 1; } /* Ignore up to 10 characters or until first space is found. */ fin.ignore(10, ' '); char c; while(fin) fin.get(c); cout << c; } fin.close();

19 Read and write blocks of binary data
Syntax for read and write n bytes of data Read n bytes of data istream & read(char *buf, streamsize num); Write n bytes of data ostream &write(const char *buf, streamsize num);

20 Example to read n block of data
#include <fstream.h> main() { int array[] = {10,23,3,7,9,11,253}; ofstream fout(“numbers.txt“, ios::out | ios::binary); fout.write((char*) &array, sizeof(array)); fout.close();

21 for(i=0; i<4; i++) // clear array
array[i] = 0; ifstream fin("numbers.txt", ios::in | ios::binary); fin.read((char *) &array, sizeof (array)); for(i=0; i<4; i++) cout << array[i] ; }

22 2)Opening Files Using Open( )
The open( ) can be used to open multiple files that use the same stream object. Syntax file-stream-class stream-object; stream-object.open ( “file_name” ); Example: { ofstream outfile; outfile.open(“DATA1”); --- outfile.open(“DATA2”); } fout.open(“Data1”, ios::app | ios :: nocreate)

23 Reading and writing objects
Void student::get() { Cin>>name>>id; } Void student::put() Cout<<name<<id; Class student { Char name[10]; int id; Public: Void get(); Void put(); }

24 Writing objects… main() { student s[10]; fstream file; file.open(“stud.txt”,ios::in|ios::out); for(int i=0;i<10;i++) s[i].get(); file.write( (char *) & s[i] , sizeof(s[i]) ); } file.seekg(0);

25 for(int i=0;i<10;i++)
{ file.read( (char *) & s[i] , sizeof(s[i]) ); s[i].put(); } file.close()

26 File Pointer – Default Actions
When a file opened in read-only mode, the input pointer is automatically set at the beginning of the file. When a file is opened in write-only mode, the existing contents are deleted and the output pointer is set at the beginning. When a file is opened in append mode, the output pointer moves to the end of file.

27 Random access files There are two pointers
Get pointer in input stream – seekg(),tellg() Put pointer in output stream- seekp(),tellp() Two functions to move this pointers seekg() function moves the associated file's current get pointer offset number of characters from the specified origin ios::beg Beginning-of-file ios::cur Current location ios::end End-of-file

28 Functions for Manipulations of File Pointers
seekg( )  Moves get pointer (input) to a specified location. seekp( )  Moves put pointer(output) to a specified location. tellg( )  Gives the current position of the get pointer. tellp( )  Gives the current position of the put pointer.

29 The seekp() function moves the associated file's current put pointer offset number of characters from the specified origin tellg() and tellp() gives the current position of the get and put pointer fout.seekg(0, ios : : beg); Go to start fout.seekg(0, ios : : cur); Stay at the current position fout.seekg(0, ios : : end); Go to the end of file fout.seekg(m, ios : : beg); Move to (m+1)th byte in the file fout.seekg(m, ios : : cur); Go forward by m bytes from the current position fout.seekg(-m, ios : : cur); Go backward by m bytes from the current position fout.seekg(-m, ios : : end) Go backward by m bytes from the end

30 Example fsream file; student s; file.open(“stud.dat”,ios::binary|ios::in|ios::out); add() { file.seekp(0L,ios::end) s.get(); file.write((char *)&s,sizeof(s)); }

31 Totalrecords() { int pos=file.tellg(); int n=pos/sizeof(s); } Display() file.seekg(0); While(file.read((char *)&s,sizeof(s)) s.put();

32 Modify() { Cout<<“enter which record to modify”; Cin>>no; Int pos=(no-1)*sizeof(s); file.seekp(pos,ios::beg); Cout<<“enter new values”; s.get(); file.write((char *)&s,sizeof(s)); }

33 Modify() While(file. read((char
Modify() While(file.read((char *)&s,sizeof(s)) { Cout<<“enter name to modify”; Cin>>name; if(strcmp(s.name,name==0)) Cout<<“enter new values”; s.get(); Int pos=(count-1)*sizeof(s); file.seekp(pos,ios::beg); file.write((char *)&s,sizeof(s)); } count++;

34 Command line arguments
int main(int argc,char * argv[]) { char ch; ifstream fin(argv[1], ios::in | ios::binary); if(!fin) { cout << "Cannot open file.";return 1;} while(fin) // in will be false when eof is reached fin.get(ch); cout << ch; }

35 Error Handling During File Operations
A file which we are attempting to open for reading does not exist. The file name used for a new file may already exist. We may attempt an invalid operation such as reading past the end-of-file. There may not be any space in the disk for storing more data. We may use an invalid file name. We may attempt to perform an operation when the file is not opened for that purpose.

36 Error handling If( fin.bad() ) //fin.good() {
//report error } While(!fin.eof()) //!fin.fail() { }

37 END Data Functions for reading file Function for writing into file
char get(); put(); 1word >>(extraction operator) << (insertion operator) line getline(); << (insertionoperator) Objects read() write()


Download ppt "C++ FILE I/O."

Similar presentations


Ads by Google