File: - The information / data stored under a specific name on a storage device, is called a file. Stream: - It refers to a sequence of bytes. Two Types of Create Files: Text file: - It is a file that stores information in ASCII characters. In text files, each line of text is terminated with a special character known as EOL (End of Line) character or delimiter character. When this EOL character is read or written, certain internal translations take place. Binary file:- It is a file that contains information in the same format as it is held in memory. In binary files, no delimiters are used for a line and no translations occur here. Basic Operation On Text File In C++ File I/O is a five-step process: 1. Include the header file fstream in the program. 2. Declare file stream object. 3. Open the file with the file stream object. 4. Use the file stream object with >>, <<, or other input/output functions. 5. Close the files. Following program shows how the steps might appear in program. Example: #include #include using namespace std; int main() { ofstream myDB("DB.text"); myDB << "Writing to file using fstream constructor!" << endl; myDB.close (); return 0; } Opening File: Opening file using constructor ofstream outFile("sample.txt"); //output only ifstream inFile(“sample.txt”); //input only Opening File Using open () StreamObject.open(“filename”, [mode]); ofstream outFile; outFile.open("sample.txt"); ifstream inFile; inFile.open("sample.txt"); function open(): fstream file; file.open ("example.dat", ios::out | ios::app | ios::binary); Closing File: outFile.close(); inFile.close();
Example: // io/read-file-sum.cpp - Read integers from file and print sum. // Fred Swartz 2003-08-20 #include #include #include using namespace std; int main() { int sum = 0; int x; ifstream inFile; inFile.open("test.txt"); if (!inFile) { cout << "Unable to open file"; exit(1); // terminate with error } while (inFile >> x) { sum = sum + x; } inFile.close(); cout << "Sum = " << sum << endl; return 0; } File Mode: Files MODES ios::in
Explanation Input mode – Default mode with ifstream and files can be read only
ios::out
Output mode- Default with ofstream and files can be write only
ios::binary ios::app
Open file as binary Preserve previous contents and write data at the end ( move forward only)
ios::ate
Preserve previous contents and write data at the end.( can move forward and backward ) ios::trunc If the file already exists, all the data will lost. ios::noreplace Open fails if the file already exist ios::nocreate The file must already exist. If file doesn't exist, it will not create new file Read from a text file and than write in another text file #include void main() { ofstream fout(“sare1.txt”); //create a file to write ifstream fin(“sare1.txt”);
fout<<“Hello….!!”; fout.close(); //closing the file fout.open(“sare2.txt”); //create file to write char ch; while(fin) //loop wiill run till end of file { fin>>ch; //reading data from file fout<
Determining End of File. eof():-Checking state flags bad():Returns true if a reading or writing operation fails. For example, in the case that we try to write to a file that is not open for writing or if the device where we try to write has no space left. fail(): Returns true in the same cases as bad(), but also in the case that a format error happens, like when an alphabetical character is extracted when we are trying to read an integer number. eof() : Returns true if a file open for reading has reached the end. good():It is the most generic state flag: it returns false in the same cases in which calling any of the previous functions would return true. Note that good and bad are not exact opposites clear(): The member function clear() can be used to reset the state flags. File Pointers And Their Manipulation: seekg() moves get pointer(input) to a specified location seekp() moves put pointer (output) to a specified location tellg() gives the current position of the get pointer tellp() gives the current position of the put pointer The other prototype for these functions is: seekg(offset, refposition ); seekp(offset, refposition ); The parameter offset represents the number of bytes(any negative or positive integer value for backward or forward movement) the file pointer is to be moved from the location specified by the parameter refposition. The refposition takes one of the following three constants defined in the ios class. ios::beg - start of the file ios::cur - current position of the pointer ios::end - end of the file
// Code to demonstrate the seekg function in file handling #include #include using namespace std; int main (int argc, char** argv) { // Open a new file for input/output operations // discarding any current in the file (assumes // a length of zero on opening) fstream myFile("test.txt", ios::in | ios::out | ios::trunc); // Add the characters "Hello World" to the file myFile << "Hello World"; // Seek to 6 characters from the beginning of the file myFile.seekg(6, ios::beg); // Read the next 5 characters from the file into a buffer char A[6]; myFile.read(A, 5); // End the buffer with a null terminating character A[5] = 0; // Output the contents read from the file and close it cout << buffer << endl; myFile.close(); }