C++ Programming Lecture 10 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. 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 ٤
The Data Hierarchy II Sally Black Tom Blue Judy Green Iris Orange Randy Red File Judy Judy 01001010 Green Field Byte (ASCII character J) Record Record key 1 Bit 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 ٦
Creating a Sequential Access File Files are opened by creating objects of stream classes ifstream, ofstream or fstream Makes a "line of File stream member functions for object file: communication" with the object and file.open( Filename, fileopenmode); the file. file.close(); closes file File open modes: Mode ios::app ios::ate ios::in ios::out ios::trunc ios::binary Description Write all output to the end of the file. Open a file for output and move to the end of the file (normally used to append data to a file). Data can be written anywhere in the file. Open a file for input. Open a file for output. Discard the file s contents if it exists (this is also the default action for ios::out) Open a file for binary (i.e., non-text) input or output. 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 ٨
Example II Storing Data Entered By the User #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); } 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; cout <<"Enter an integer to save on file\n"; cin >> a; 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 fileobject fileobject.seekg( n, ios::cur ); // position y bytes back from end of fileobject fileobject.seekg( y, ios::end ); // position at end of fileobject fileobject.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 ١٤
Updating Sequential Access Files Sequential access file Cannot be modified without the risk of destroying other data 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 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) setw stream 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 ٢٢