1 / 37

Simple File I/O

Simple File I/O. Objective. Learn to Create and use disk files to store program input How to read such data in a program How to specify and declare file variables How to save program output to disk files. External Stream File. File acts as Input Output. Filenames and file variables.

richardn
Download Presentation

Simple File I/O

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. Simple File I/O

  2. Objective • Learn to • Create and use disk files to store program input • How to read such data in a program • How to specify and declare file variables • How to save program output to disk files

  3. External Stream File • File acts as • Input • Output

  4. Filenames and file variables • First step in using a disk file for program output is • Choose an appropriate filename • Appropriate filename depend on operating system • DOS • Filename.Extension • 8 Letters.3 Letters

  5. Extension • Extension • C++ source file -- .cpp • Executable file -- .exe • Disk file • Used to store program output information • No standard file extension • .dat -- data • .txt -- textual information

  6. Extension • Common DOS and Windows file extensions • .com -- execution file • .obj -- object binary file • .ini -- Windows information file • .bat -- DOS batch command file • .sys -- system file

  7. Naming filename • Choose a filename that reflects the type and purpose of the information contained within the file • grade.txt • Contain grades in text form grade.txt A B A

  8. Stream Access 1 • First step • Include the appropriate header file #include <fstream.h> • fstream.h already contains a #include <iostream.h> • Second step • Declare file variable ofstream variable;

  9. Stream Access 2 • Third step • Open disk file variable.open(filename); • Open() command • Causes C++ to formulate a request to the OS to open the indicated file

  10. Stream Access 3 • Example ofstream newfile; newfile.open(“grades.txt”); • Variable newfile • Keep track of the state of the file during execution • Filename may include a disk drive specifier/or a directory path newfile.open(“a:\grades.txt”);

  11. Stream Access 4 • Fourth Step • Write to disk file newfile << “this is written to disk file” << endl; cout << “this is written to screen” << endl;

  12. Sample Program 1 #include <iostream.h> #include <fstream.h> void main() { char done = ‘y’; int acnt_num; float balance; ofstream outfile; outfile.open(“accnts.dat”);

  13. Sample Program 1 (Cont.) while (done != ‘n’) { cout << “Enter an account number and balance: “; cin >> acnt_num >> balance; outfile << acnt_num << “ “ << balance << endl; cout << “Another account?”; cin >> done; } }

  14. Screen Output enter an account number and balance: 345 678.90 another account? Y enter an account number and balance: 123 456.78 another account? Y enter an account number and balance: 901 234.56 another account? n accnts.dat 345 678.9 123 456.78 901 234.56

  15. Record • Each account is represented by 2 pieces of information • Account number • Balance • Each group of related information called record

  16. Input Files • Input file declaration ifstream variable; Ex. ifstream infile; • Open file Ex. infile.open(“accnts.dat”); • Input is accomplished using • >> (Extraction Operator) Ex. infile >> acntnum >> balance;

  17. Sample Program 2 #include <iostream.h> #include <fstream.h> void main() { int acnt_num; float balance; int n; float sum = 0.0; ifstream infile;

  18. Sample Program 2 (Cont.) infile.open(“accnts.dat”); for (n=0; n<3; n++) { infile >> acnt_num >> balance; sum += balance; } cout << “The total of all accounts is: “ << sum << endl; }

  19. Sample Program 3 #include <iostream.h> #include <fstream.h> void main() { int acnt_num,search; float balance; ifstream infile; int n, done = 0; infile.open(“accnts.dat”); cout << “Enter account number: “; cin >> search;

  20. Sample Program 3 (cont.) for (n=0; n<3 && !done; n++) { infile >> acnt_num >> balance; if (acntnum == search) { cout << “balance is : “ << balance << endl; done = true; } } {

  21. End-of-file loops • Consider code segment infile.open(“accnts.dat”); while (infile >> acntnum >> balance) sum += balance; cout << “The total balance of all accounts is: “ << sum << endl; • Extraction operator will return false when • File is empty • File is closed • File doesn’t contain the correct type or number of data values you have indicated should be read

  22. Type or number of data items doesn’t match the variables that are to be filled accnts2.dat 345 678.90 x 456.78 901 234.56 System expect to find an integer and real number Extraction fails on the second record

  23. Closing Files • Good operating system attempt to minimize the number of times a disk access is made by • Pooling operation until a larger number of requests can be blocked together • In reserved location in memory, called buffer • When buffer is full, system will then perform one disk access to write the entire buffer

  24. Code Segment ofstream outfile; ifstream infile; outfile.open(“somefile.dat”); outfile << 55 << 66 << 77; infile.open(“somefile.dat”); infile >> x >> y >> z; • There is a way to indicate that no more output is to be expected and cause the system to flush the buffer out to the disk • variable.close( );

  25. Update Code Segment ofstream outfile; ifstream infile; outfile.open(“somefile.dat”); outfile << 55 << 66 << 77; outfile.close( ); infile.open(“somefile.dat”); infile << x << y << z;

  26. Output Formatting 1 #include <iostream.h> #include <fstream.h> void main() { float value=789.357; cout << "Item cost"; cout.fill('.'); cout.precision(5); cout.width(12); cout<<value; } Output: Item Cost ……789.36

  27. Output Formatting 2 #include <iostream.h> #include <fstream.h> #include <math.h> const int PRECISION = 4; const int WIDTH1 = 10; const int WIDTH2 = 15; void main() { float value,root; ifstream infile ("values.dat“); cout << " value square root“ <<endl; cout.precision(PRECISION); Values.dat: 25.0 16.5 18.4 199.233 234.567 123452.3

  28. Output Formatting while (infile >> value) { root = sqrt(value); cout.width(WIDTH1); cout << value; cout.width(WIDTH2); cout << root << endl; } } Output: value square root 25 5 16.5 4.062 18.4 4.29 199.2 14.11 234.6 15.32 1.235e+05 351.4

  29. Standard Error Stream #include <iostream.h> #include <fstream.h> void main() { int age; cout << “Enter age:”; cin >> age; if (age <0) cerr << "**ERROR; an illegal age has been entered"; }

  30. Member Function • General Function • sqrt(4) • sqrt is a function name • 4 is an argument • C++ can represent things in nature with • Simple variable • Class • Notice • Outfile.open(“somefile.dat”);

  31. Member Function (cont.) • Simple variable might hold a value • Class can be used to represent • State or value • Operations • Class might own a set of functions which act on that value • cin and cout are instances of a class • cin is an instance of the ifstream class • cout is an instance of the ofstream class

  32. Member Function (cont.) • Each class instance is allowed to have its own set of functions, called member functions ofstream outfile; outfile.precision(4); …………………… Tool lathe; lathe.precision(10);

  33. Member Function (cont.) • Functions dealing with files (open(), close(), precision(), width(), fill() • Must all be invoked by preceding them with the associated file variable name (class instance) and a dot

  34. Sample Project #include <iostream.h> #include <fstream.h> const int END = -1; void Makelist (int patID, ifstream& patfile, ofstream& outfile) { int drug, id; patfile >> id; while (patfile && id != patID) patfile >> id; if (patfile) { patfile >> drug; while (drug >0) { outfile<<" "<<drug; patfile >> drug; } } }

  35. void FindDrug (ifstream& drugfile, int newdrug) { int thisdrug; drugfile >> thisdrug; while (drugfile && thisdrug != newdrug) { drugfile >> thisdrug; while (thisdrug > 0) drugfile >> thisdrug; drugfile >> thisdrug; } }

  36. bool CurrentlyTaking (int contradrug) { int currently_taking; bool found = false; ifstream fin ("temp.txt", ios::in); while (fin >> currently_taking && !found) if (currently_taking == contradrug) found = 1; fin.close(); return found; }

  37. void main() { int patID, newdrug, contradrug; ifstream patfile ("patients.txt", ios::in); ifstream drugfile ("drugs.txt", ios::in); ofstream outfile ("temp.txt", ios::out); cout << "enter patient ID and drug number: "; cin >> patID >> newdrug; Makelist (patID, patfile, outfile); outfile.close(); FindDrug(drugfile, newdrug); if (drugfile) if (drugfile >> contradrug) while (contradrug > 0) { if (CurrentlyTaking(contradrug)) cout << "*WARNING: drug interaction possible!" << endl; drugfile >> contradrug; } }

More Related