Input and Output File (Files and Stream ) BITE 1513 Computer Game Programming Week 14
Scope Describe the fundamentals of input & output files. Use data files for input & output purposes.
Files Normally, it is difficult to handle large amounts of input data and output data and would always be lost as soon as we turned off the computer. We can use a file instead of keyboard for program input. The file is called input file. We can use a file instead of monitor screen for program output. The file is called output file. File a collection of related data usually stored in secondary storage devices such as Disk, Tape, etc. Purpose to keep data in a secondary storage.
Files Using file, data can be created by one program, stored (or saved) on secondary devices, and then accessed or modified by other programs when necessary. Two major characteristics of files are: Text files : data in text format Binary files : data in binary format Files in a secondary storage can be both read and written. These processes are also known as input/output.
Types of File Stream The type of stream class determines if it is an input file or an output file or both. ofstream output file stream class. Creating files and writing data to them (output file). ifstream input file stream class. Opening existing and reading data from them into memory (input file). fstream file stream class. Creating files, writing data to them and reading data from them (both input & output file).
What are the steps needed to Use Files? Include the <fstream> header file Define a file stream object using appropriate file stream class Open the file Use the file Close the file
Include the <fstream> header file Standard input stream (cin) and standard output stream (cout) requires the <iostream> header file. File input/output stream both requires <fstream> header file. Define a file stream object using appropriate file stream class ( ifstream / ofstream / fstream ) A file is identified by its file name, e.g. student.dat Inside a C++ program, a file is identified by a file stream object. eg: ifstream infile; // infile is an input file stream // object, with ifstream class eg: ofstream outfile;// outfile is an output file // stream object, with ofstream class
Opening a File : input / output file The object is then linked to the actual file as follows: infile.open( student.dat ); outfile.open( student_new.dat ); Alternative : statements found in (2) & (3) could be combined as the following statements: ifstream infile( student.dat ); ofstream outfile( student_new.dat );
Input / Output : File Name vs File Stream Object
File name (example) ifstream myinputfile; char filename[20]; cout << Enter name of the data file: ; cin >> filename; myinputfile.open(filename); OR char filename[20]; cout << Enter name of the data file: ; cin >> filename; ifstream infile(filename);
Open File Modes There are a few modes to open a file. They are listed as follows: Mode and Description ios::in Input mode. Data will be read from the file. The file MUST exists. If the file doesn t exist, it will not be created and the open function fails. ios::out Output mode. Data will be written to the file. The file will be created if it does not exist. If it already exists, the file s content will be deleted and replaced by the new data. ios::app Append mode. If the file already exists, its contents are preserved and all output is written to the end of the file. If the file doesn t exist, it will be created
More on Open File Mode All these modes can be combined using the operator (which means OR). For example, if we want to open the file example.bin to add data we could do it by the following statement : ofstream myfile("example.bin", ios::out ios::app);
More on Open File Mode For all file stream classes, default mode/s is/are automatically applied if the file is opened without specifying any value for the mode parameter. Stream class Default mode parameter ofstream ios::out ifstream ios::in fstream ios::in ios::out More on Open File Mode 13
Use the file Can use output file stream object and << to send data to a file outfile << "Inventory report"; Can use input file stream object and >> to copy data from file to variables infile >> partnum; infile >> qtyinstock >> qtyonorder;
Closing a File When we are finished with our input and output operations on a file we should close it. When a file is closed, any unsaved data in the buffer will be saved to its file. Closing a file improves system s performance (the operating system s resources is better utilized.) Use the close member function infile.close(); outfile.close(); After closing a file, the file stream object (above eg: infile and outfile) can be used again to open another file.
Example of Output File Writing output to a text file : Example 1 # include <iostream> # include <fstream> using namespace std; int main() { double income = 123.45, expenses = 987.65; int week = 7, year = 2006; ofstream outfile("l4_2.out");// default mode is ios::out outfile<<"week = "<<week<<endl<<"year = "<<year<<endl; outfile<<"income = "<<income<<endl<<"expenses = "<<expenses<<endl; outfile.close(); return 0;
Example of Output File: More on Example 1 Content of L4_2.out text file : You can find the L4_2.out file in the same folder as the C++ program that wrote the file. Open it using the notepad.
Writing output to a text file : Example 2 #include <iostream> #include <iomanip> #include <fstream> using namespace std; int main () { { } char name[20]; char id[10]; float m1,m2; ofstream datafile ( student.txt", ios::out); cout<<"enter student's id, name, first mark and second mark."; cout<<"\npress <ctrl> + z to stop.\n"; while (cin >> id >> name >> m1 >> m2) //reading from keyboard using EOF while loop datafile.close(); return 0; } datafile << setw(10)<<id<<setw(20)<<name<<setw(5)<<m1<<setw(5)<<m2<<endl;
For example the input of the program is entered as follows :
Input Files Input files can be also created using any text editor. Notepad is an example of text editor you can use to save your data. To create an input file using a text editor, open the notepad and type the data. Save the file in the same folder with the C++ program that will use these data. Example of the file is shown below:
Reading data from a text file: Example 1 { #include <iostream> #include <fstream> #include <iomanip> using namespace std; int main() double x; int i,j; ifstream infile1("l4_3a.dat"); ifstream infile2("l4_3b.dat"); infile1>>i>>j>>x; infile1.close(); cout<<"from first file i = "<<i<<", j = "<<j<<", x = "<<x<<endl; infile2>>i>>j>>x; infile2.close(); cout<<"from second file i = "<<i<<", j = "<<j<<", x = "<<x<<endl; return 0; }
Example 2 #include <iostream> #include <fstream> #include <cstring> using namespace std; int main () { char line[50]; ifstream myfile ("example.txt"); if (myfile.is_open()) //checking file existance { while (! myfile.eof() ) // checking EOF for myfile using while loop { myfile.getline (line,50); //read string from myfile cout << line << endl; } } cout<<endl; myfile.close(); else cout << "Unable to open file"; return 0; }