220 likes | 230 Views
C++ Programming Lecture 8 File Processing. By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department. Outline. Introduction. The Data Hierarchy. Files and Streams. Creating a Sequential Access File. Reading Data from a Sequential Access File.
E N D
C++ ProgrammingLecture 8File Processing By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department
Outline • Introduction. • The Data Hierarchy. • Files and Streams. • Creating a Sequential Access File. • Reading Data from a Sequential Access File. • Updating Sequential Access Files. • Input/Output Manipulations. • Examples. The Hashemite University
Introduction • Data files can be created, updated, and processed by C++ programs • Files are used for permanent storage of large amounts of data • Storage of data in variables and arrays is only temporary The Hashemite University
The Data Hierarchy I • Bit - smallest data item • value of 0 or 1 • Byte – 8 bits • used to store a character • Decimal digits, letters, and special symbols • Field - group of characters conveying meaning • Example: your name • Record – group of related fields • Represented as a struct or a class • Example: In a payroll system, a record for a particular employee that contained his/her identification number, name, address, etc. • File – group of related records • Example: payroll file • Database – group of related files The Hashemite University
Sally Black Tom Blue Judy Green File Iris Orange Randy Red Judy Green Record Judy Field 01001010 Byte (ASCII character J) 1 Bit The Data Hierarchy II • Record key • identifies a record to facilitate the retrieval of specific records from a file • Sequential file • records typically sorted by key The Hashemite University
Files and Streams • C++ views each file as a sequence of bytes • File ends with the end-of-file marker • Stream is created when a file is opened • File processing • Headers <iostream> and <fstream> • class ifstream - input • class ofstream - output • class fstream - either input or output The Hashemite University
Makes a "line of communication" with the object and the file. Creating a Sequential Access File • Files are opened by creating objects of stream classes ifstream, ofstream or fstream • File stream member functions for object file: • file.open(“Filename”, fileOpenMode); • file.close(); • closes file • File open modes: The Hashemite University
Example I #include<iostream> #include<fstream> using namespace std; int main() { ofstream out_file("HU.txt", ios::out); //or HU.dat if(out_file == 0) { cout <<"Unable to open the file\n"; exit(1); } for(int i = 0; i < 9; i++) out_file << i << endl; out_file.close(); return 0; } The Hashemite University
#include<iostream> #include<fstream> using namespace std; int main() { ofstream out_file("HU.txt", ios::in); //or HU.dat int a; if(out_file == 0) { cout <<"Unable to open the file\n"; exit(1); } cout <<"Enter an integer to save on file\n"; cin >> a; while(a != -1) //end when -1 is entered { out_file << a << endl; cout <<"Enter an integer to save on file\n"; cin >> a; } out_file.close(); return 0; } Example II – Storing Data Entered By the User The Hashemite University
Notes • You will find the created text file in the same directory in which you save the source code unless you specify the full path of where you want to save the created text file. • The extension of the created file could be .txt or .dat • Pay attention to how the data is written on the file (wether there are formatted, only one value is stored per line or multiple ones, etc.) to read the data correctly. • All attributes associated with cin object (stopping at enetr or white spaces, read vales based on the data type of the holder, etc.) are applied to files reading. • ofstream are opened for output by default.so, in the previous example writing ofstream out_file("HU.txt"); is the same as ofstream out_file("HU.txt", ios::out); The Hashemite University
Reading Data from a Sequential Access File • File stream member functions for repositioning file position pointer: • seekg (seek get) for istream and seekp (seek put) for ostream • // position to the nth byte of fileObject // assumes ios::beg fileObject.seekg( n ); • // position n bytes forward in fileObjectfileObject.seekg( n, ios::cur ); • // position y bytes back from end of fileObjectfileObject.seekg( y, ios::end ); • // position at end of fileObjectfileObject.seekg( 0, ios::end ); • tellg and tellp – return current location of pointer location = fileObject.tellg() //returns long int The Hashemite University
Example #include<iostream> #include<fstream> using namespace std; int main() { ifstream in_file("HU.txt", ios::in); //or HU.dat int a; if(in_file == 0) { cout <<"Unable to open the file\n"; exit(1); } for(int i = 0; i < 9; i++) { in_file >> a; cout << a << endl; } in_file.close(); return 0; } The Hashemite University
Example Output The Hashemite University
Note • The file that you read from must be stored in the same directory in which you store the source code file, otherwise you must specify the full path of where you store the file. • The extension of the created file could be .txt or .dat • ifstream are opened for input by default. so, in the previous example writing ifstream in_file("HU.txt"); is the same as ifstream in_file("HU.txt", ios::in); The Hashemite University
300 White 0.00 400 Jones 32.87 (old data in file) if we want to change White's name to Worthington, 300 Worthington 0.00 300 White 0.00 400 Jones 32.87 300 Worthington 0.00ones 32.87 Data gets overwritten Updating Sequential Access Files • Sequential access file • Cannot be modified without the risk of destroying other data • Formatted text which is output to a file is very different than the internal representation The Hashemite University
Input/Output Manipulations • C++ provides various stream manipulators that perform formatting tasks. • Till now we have dealt with screen output using cout. So, all these manipulators will format the text that appears on the screen. • Examples: • Setting the precision of the displayed floating point numbers. • Setting the field width. • Showing trailing zeros and decimal point in floating point numbers. • Filling field with specific characters. The Hashemite University
Floating-Point Precision(setprecision) • setprecision • sets number of digits to the right of decimal point (with rounding) • parameterized stream manipulator • Like all parameterized stream manipulators, <iomanip> required • specify precision: cout << setprecision(2) << x; • Changes last until a different value is set. The Hashemite University
Field Width(setw) • setwstream manipulator • sets field width (number of character positions a value should be output or number of characters that should be input). • returns to previous width after the implementation (so it is applied to the next insertion or extraction only). • If values processed are smaller than width, fill characters inserted as padding. • Large values are not truncated - full number printed. • Displayed output is right justified. • Examples: cin >> setw(5) >> number; cout << setw(5) << number; The Hashemite University
Trailing Zeros and Decimal Points (showpoint) • ios::showpoint • forces a float with an integer value to be printed with its decimal point and trailing zeros cout << showpoint << 79.0; will print 79.00000 • number of zeros determined by precision settings • Applied for all subsequent output operations. • To reset this option apply the following command: cout << noshowpoint; • Remember trailing zeros are applied to floating point numbers only and not for integers. The Hashemite University
Padding (setfill) • If you specify the field width to 10 and you print 56 then this number will be preceded by white spaces. • White space here is the fill character. • You can change this fill character to any other character you want. • Applied for all subsequent cout statements. To remove it set the fill character to white space to return to the default settings. • setfill manipulator • sets fill character cout << setfill ('*'); cout << setw(5) << 3; //output is ****3 The Hashemite University
Floating-Point Numbers; Scientific Notation (scientific, fixed) • scientific • forces output of a floating point number in scientific notation: • 1.946000e+009 • Only one digit in the integer part of the floating point number and n digits after the floating point (depends on the precision value) and put the suitable power after the e exponent. • E.g.: cout << scientific << 234.5678; • fixed • forces floating point numbers to display a specific number of digits to the right of the decimal (specified with precision) and the whole integral part. • E.g.: cout << fixed << 234.5e-1; • Applied for all subsequent cout statements. • The default setting in C++ is the fixed formatting or depends on the original value of the floating point number. The Hashemite University
Additional Notes • This lecture covers the following material from the textbook: • Chapter 14: Sections 14.1 – 14.6 • Chapter 12: Sub-Sections 12.6.2, 12.6.3, 12.7.1, 12.7.3, 12.7.5 • This is the last lecture included in the first exam material. The Hashemite University