What Is File? A file is a collection on information, usually stored on a computer's disk. Information can be saved to files and then later reused.
The following classes in C++ have access to file input and output functions: fstream Ifstream ofstream
DIFFERENT FILE OPERATIONS OPENING A FILE CLOSING A FILE READING FROM A FILE WRITING ON A FILE CHECKING FOR END OF FILE
OPENING A FILE 1.By using the CONSTRUCTOR of the stream class. ifstream transaction(“xyz.txt"); ofstream result ("result.02"); 2.By using the open() function of the stream class ifstream transaction; transaction.open (“xyz.txt");
Checking For Successful File Opening ifstream transaction("sale.txt"); if ( transcation == NULL) { cout <<"unable to open sales.txt"; cin.get (); //waits for the operator to press any key exit(0); }
Reading from a file // Print each character read from the file char ch ; while ( file.get ( ch )) { cout << ch ; }
WRITE TO A FILE // Method 1: Using the << operator outputFile << "Hello, world!" << endl ; outputFile << "This is a new line." << endl ; // Method 2: Using the write() function const char* message = "Another way to write to a file."; outputFile.write (message, strlen (message));
Closing of File Stream name.close (); e.g., transaction.close ();
File Mode Parameters MODES MEANINGS ios ::app Append to end-of file ios ::ate Goto end of file on opening ios ::binary Binary file ios ::in Open existing file for reading ios :: nocreate Open fails if file doesn't exist ios :: noreplace Open fails if file already exists ios ::out Open existing file for writing ios :: trunc Deletes contents if it exists The mode can combine two or more modes using bit wise or (l)
Types of Files The two basic types of files are 1.Text File & 2.Binary File
Text File Binary File When using a text file, we write out separately each of the pieces of data about a given record. The text file will be readable by an editor. for the text file we will use the usual output operator(<<) and will output each of the pieces of the record separately. with the text file we will read each of the pieces of record from the file separately, using the usual input operator(>>) When using a Binary file we write whole record data to the file at once. But the numbers in the binary file will not be readable in this way. For the binary file we will use write to write to the file. With the binary file we will use the read function to read a whole record.