1 / 34

File Handling

File Handling. Introduction. Data stored in variables, arrays, and objects are temporary, lost when the program terminates To permanently store data created in a program, it is required to save in file

delk
Download Presentation

File Handling

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. File Handling

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

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

  4. Writing to File

  5. Reading from File

  6. Setting Up a Program for File Input/Output Before file I/O can be performed, a C++ program must be set up properly File access requires the inclusion of <fstream.h> or <fstream> 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

  7. 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.

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

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

  10. File Modes

  11. File Modes

  12. File Modes

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

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

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

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

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

  18. File writing using << - Example #include <iostream.h> #include <fstream.h> void main( ) { fstreamdataFile; dataFile.open(“D:\\TestFile.txt", ios::out); if (!dataFile) { cout << "File open error!" << endl; return; } cout << "File opened successfully.\n"; cout << "Now writing information to the file.\n"; dataFile<< "Jones\n"; dataFile<< "Smith\n"; dataFile<< “Willis\n"; dataFile<< "Davis\n"; dataFile.close(); cout << "Done.\n"; }

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

  20. File Storage in TestFile.txt

  21. Example - Append #include <iostream.h> #include <fstream.h> void main( ) { fstream dataFile; dataFile.open(“d:\\TestFile.txt", ios::out); dataFile << "Jones\n"; dataFile << "Smith\n"; dataFile.close(); dataFile.open(" d:\\TestFile.txt ", ios::app); dataFile << “Willis\n"; dataFile << "Davis\n"; dataFile.close(); } Output Jones Smith Willis Davis

  22. File Output Formatting File output may be formatted the same way as screen output. #include <iostream.h> #include <fstream.h> void main( ) { fstreamdataFile; float num = 123.456; dataFile.open(" d:\\TestFile.txt ", ios::out); if (!dataFile) { cout<< "File open error!" << endl; return; } dataFile<< num << endl; dataFile.precision(5); dataFile<< num << endl; dataFile.precision(4); dataFile<< num << endl; dataFile.precision(3); dataFile<< num << endl; dataFile.close(); } Output 123.456 123.46 123.5 124

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

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

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

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

  27. getline Member Function dataFile.getline(str, 81, ‘\n’); str – Name of a character array. Information read from file will be stored here. 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’ – 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.)

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

  29. 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 dataFile(" d:\\TestFile.txt ", ios::in); char input[81]; dataFile.getline(input, 81, '$'); while (!dataFile.eof()) { cout << input << endl; dataFile.getline(input, 81, '$'); } dataFile.close(); }

  30. 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

  31. Character I/O

  32. The get and put Member Function inFile.get(ch);//one character at a time //Reads or inputs one character at a time from the file outFile.get(ch); //one character at a time //Writes or outputs one character at a time to the file

  33. 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(){ fstreamfile; char ch, fileName[51]; cout<< "Enter a file name: "; cin>> fileName; // d:\\TestFile.txt file.open(fileName, ios::in); if (!file){ cout<< fileName << “ 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(); }

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

More Related