File Handling Introduction n Data stored in variables

File Handling

Introduction n Data stored in variables, arrays, and objects are temporary, lost when the program terminates n To permanently store data created in a program, it is required to save in file n A file is a collection on information, usually stored on a computer’s disk. Information can be saved to files and then later reused. n All files are assigned a name that is used for identification purposes by the operating system and the user. For example, First. Prog. cpp, Marks. txt, Student. doc etc.

Basic File Operations n Opening a file n Writing to a file n Reading from a file n Close a file . . .

Writing to File

Reading from File

Setting Up a Program for File Input/Output n Before file I/O can be performed, a C++ program must be set up properly n File access requires the inclusion of <fstream. h> or <fstream> n When working with files in C++, the following classes can be used: ¨ ¨ ¨ ofstream – writing to a file ifstream – reading from a file fstream – reading / writing

Stream class Hierarchy A stream is a general name given to a flow of data. In C++, a stream is represented by an object of a particular class. So far we’ve used the cin and cout stream objects.

Opening a File n Before data can be written to or read from a file, the file must be opened. ofstream output. File; output. File. open(“Record. txt”); OR ofstream output. File; output. File. open(“d: \Record. txt”); Open function opens a file if it exists previously, otherwise it will create that file

Opening a File – Example #include <iostream. h> #include <fstream. h> void main( ) { fstream data. File; //Declare file stream object char file. Name[25]; cout << "Enter name of file to open or create”; cin. getline(file. Name, 25); data. File. open(file. Name, ios: : out ); cout << "The file “<<file. Name<<" was opened. "; } File modes

File Modes

File Modes

File Modes

Opening a File at Declaration #include <iostream. h> #include <fstream. h> void main( ) { fstream data. File(“Names. txt", ios: : in | ios: : out); cout << "The file names. txt was opened. n"; }

Testing for Open Error #include <iostream. h> #include <fstream. h> void main( ) { fstream data. File; data. File. open(“Student. dat”, ios: : in); } if (!data. File) { cout << “Error opening file. n”; }

Another way to Test for Open Error #include <iostream. h> #include <fstream. h> void main( ) { fstream data. File; data. File. open(“Student. dat”, ios: : in); } if (data. File. fail()) { cout << “Error opening file. n”; }

Closing a File A file should be closed when a program is finished using it. void main() { fstream data. File; data. File. open(“My. File. txt", ios: : out); if (!data. File) { cout << "File open error!”<<endl; return; } cout << "File was created successfullyn"; cout << "Now closing the filen"; data. File. close(); }

Using << to Write Information to a File n The stream insertion operator (<<) may be used to write information to a file. output<<“I like Programming !”; fstream object

File writing using << - Example #include <iostream. h> #include <fstream. h> void main( ) { fstream data. File; data. File. open(“D: \Test. File. txt", ios: : out); if (!data. File) { cout << "File open error!" << endl; return; } cout << "File opened successfully. n"; cout << "Now writing information to the file. n"; data. File<< "Jonesn"; data. File<< "Smithn"; data. File<< “Willisn"; data. File<< "Davisn"; data. File. close(); cout << "Done. n"; }

Program Screen Output File opened successfully. Now writing information to the file. Done. Output to File Test. File. txt Jones Smith Willis Davis

File Storage in Test. File. txt

Example - Append #include <iostream. h> #include <fstream. h> void main( ) { fstream data. File; } data. File. open(“d: \Test. File. txt", ios: : out); data. File << "Jonesn"; data. File << "Smithn"; data. File. close(); data. File. open(" d: \Test. File. txt ", ios: : app); data. File << “Willisn"; data. File << "Davisn"; data. File. close(); Output Jones Smith Willis Davis

File Output Formatting n File output may be formatted the same way as screen output. #include <iostream. h> #include <fstream. h> void main( ) { fstream data. File; float num = 123. 456; data. File. open(" d: \Test. File. txt ", ios: : out); if (!data. File) { cout << "File open error!" << endl; return; } data. File << num << endl; data. File. precision(5); data. File << num << endl; data. File. precision(4); data. File << num << endl; data. File. precision(3); data. File << num << endl; data. File. close(); } Output 123. 456 123. 46 123. 5 124

Using >> to read information from a File n The stream extraction operator (>>) may be used to read information from a file. #include <iostream. h> #include <fstream. h> void main( ) { string name; fstream data. File; data. File. open(“d: \Test. File", ios: : in); if (!data. File) { cout << "File open error!" << endl; return; } cout << "File opened successfully. n"; cout << "Now reading information from the file. nn"; for (int count = 0; count < 4; count++) { data. File >> name; cout << name << endl; } data. File. close(); cout << "n. Done. n"; }

Using >> to read information from a File (Output) File opened successfully. Now reading information from the file. Jones Smith Willis Davis Done.

Detecting the End of a File n The eof() member function reports when the end of a file has been encountered. if (in. File. eof()) in. File. close();

About eof() n In C++, “end of file” doesn’t mean the program is at the last piece of information in the file, but beyond it. n The eof() function returns true when there is no more information to be read.

getline Member Function data. File. getline(str, 81, ‘n’); n str – Name of a character array. Information read from file will be stored here. n 81 – This number is one greater than the maximum number of characters to be read. In this example, a maximum of 80 characters will be read. n ‘n’ – This is a delimiter character of your choice. If this delimiter is encountered, it will cause the function to stop reading. This argument is optional If it’s left out, ‘n’ is the default. )

getline Member Function - Example #include <iostream. h> #include <fstream. h> void main( ) { fstream name. File; char input[81]; } name. File. open(“d: \Test. File. txt", ios: : in); if (!name. File){ cout << "File open error!" << endl; return; } name. File. getline(input, 81); // use n as a delimiter while (!name. File. eof()){ cout << input << endl; name. File. getline(input, 81); // use n as a delimiter } name. File. close(); Output Jayne Murphy 47 Jones Circle Almond, NC 28702

Example – getline Function with User defined Delimiter // This file shows the getline function with a user-specified delimiter. #include <iostream. h> #include <fstream. h> void main( ) { fstream data. File(" d: \Test. File. txt ", ios: : in); char input[81]; data. File. getline(input, 81, '$'); while (!data. File. eof()) { cout << input << endl; data. File. getline(input, 81, '$'); } data. File. close(); }

getline Function with User defined Delimiter (Output) Jayne Murphy 47 Jones Circle Almond, NC 28702 Bobbie Smith 217 Halifax Drive Canton, NC 28716 Bill Hammet PO Box 121 Springfield, NC 28357

Character I/O

The get and put Member Function n in. File. get(ch); n out. File. get(ch); //one character at a time //Reads or inputs one character at a time from the file //one character at a time //Writes or outputs one character at a time to the file

The get Member Function - Example // This program asks the user for a file name. The file is // opened and its contents are displayed on the screen. #include <iostream. h> #include <fstream. h> void main(){ fstream file; char ch, file. Name[51]; cout << "Enter a file name: "; cin >> file. Name; // d: \Test. File. txt file. open(file. Name, ios: : in); if (!file){ cout << file. Name << “ could not be opened. n"; return; } file. get(ch); // Get a character while (!file. eof()){ cout << ch; file. get(ch); // Get another character } file. close(); }

The put Member Function - Example // This program demonstrates the put member function. #include <iostream. h> #include <fstream. h> void main(void) { fstream data. File("sentence. txt", ios: : out); char ch; cout<< "Type a sentence and be sure to end it with a period"; while (1) { cin. get(ch); data. File. put(ch); if (ch == '. ') break; } data. File. close(); }
- Slides: 34