370 likes | 396 Views
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.
E N D
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 • 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
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
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
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
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;
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
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”);
Stream Access 4 • Fourth Step • Write to disk file newfile << “this is written to disk file” << endl; cout << “this is written to screen” << endl;
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”);
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; } }
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
Record • Each account is represented by 2 pieces of information • Account number • Balance • Each group of related information called record
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;
Sample Program 2 #include <iostream.h> #include <fstream.h> void main() { int acnt_num; float balance; int n; float sum = 0.0; ifstream infile;
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; }
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;
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; } } {
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
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
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
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( );
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;
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
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
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
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"; }
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”);
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
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);
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
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; } } }
void FindDrug (ifstream& drugfile, int newdrug) { int thisdrug; drugfile >> thisdrug; while (drugfile && thisdrug != newdrug) { drugfile >> thisdrug; while (thisdrug > 0) drugfile >> thisdrug; drugfile >> thisdrug; } }
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; }
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; } }