Chapter Seven File Operations (File Input/output) Computer Programming By Leweyehu Y.
Introduction A file is a collection of related data stored in a particular area on the disk. Programs can be designed to perform read or write operations on these files. This involves two kinds of data communication: 1 . Data transfer between the console unit and the program 2. Data transfer between the program and a disk file. By Leweyehu Y.
A file can be defined by following class ifstream , ofstream , fstream , all these are defined in fstream header file. If a file object is declared by ifstream class, then that object can be used for reading from a file . If a file object is declared by ofstream class, then that object can be used for writing onto a file . If a file object is declared by fstream class then, that object can be used for both reading from and writing to a file By Leweyehu Y.
In C++, I/O system supplies an interface to the programmer that is independent of the actual device (terminals, disks, tape drives) being accessed. This interface is known as stream . A stream is a sequence of bytes . It acts as either as a source from which the input data can be obtained or as a destination to which the output data can be sent. The source stream that provides data to the program is called input stream and the destination stream that receives output from the program is called the output stream . A program extracts the bytes from an input stream and inserts bytes into an output stream. Input Device Output Device Program Output stream Input stream Extraction from input stream Insertion into output stream. Figure: Data streams Stream Classes and I/O operations By Leweyehu Y.
By Leweyehu Y.
ios : General input/output stream class. Contains basic facilities that are used by all other input and output classes. Declares constants and functions that are necessary for handling formatted input and output operations. istream (input stream): Inherits the properties of ios . Declares input functions such as get() , getline () and read() . Contains overloaded extraction operator >> ostream (output stream): Inherits the properties of ios . Declares output functions such as put() and write() . Contains overloaded insertion operator << iostream (input/output stream): Inherits the properties of ios , istream and ostream By Leweyehu Y.
Table File mode parameters parameter Meaning ios:: app Append to end-of-file ios ::ate Go to end-of-file on opening ios::binary Binary file ios::in open file for reading only ios::nocreate Open fails if the file does not exist ios::noreplace Open fails if the file already exists ios::out Open file for writing only ios :: trunc Delete contents of the file if it exists By Leweyehu Y.
File basic operation open file #include < iostream > #include < fstream > using namespacestd ; int main () { ofstream myfile ; myfile.open ("example.txt"); myfile << "Writing this to a file.\n"; myfile.close (); return0; } By Leweyehu Y.
Writing this to a file This code creates a file called example.txt and inserts a sentence into it in the same way we are used to do with cout , but using the file stream myfile instead. Opening a file The first operation generally performed on an object of one of these classes is to associate it to a real file. By Leweyehu Y.
This procedure is known as to open a file. In order to open a file with a stream object we use its member function open(): open (filename, mode); ofstream myfile ; myfile.open ("example.txt", ios ::out | ios ::app | ios ::binary); By Leweyehu Y.
Example 1: Writing a single line to a file #include <iostream> #include <fstream> using namespace std; int main() { ofstream outputFile("output.txt"); if (outputFile.is_open()) { outputFile << "Hello, World!"; // Write a single line to the file outputFile.close(); cout << "Data written to the file successfully." <<endl; } else { cout << "Failed to open the file." << endl; } return 0;} By Leweyehu Y.
Example 2: Writing multiple lines to a file #include <iostream> #include <fstream> using namespace std; int main() { ofstream outputFile("output.txt"); if (outputFile.is_open()) { outputFile << "Line 1\n"; outputFile << "Line 2\n"; outputFile << "Line 3\n"; outputFile.close(); cout << "Data written to the file successfully." << endl; } else { std::cout << "Failed to open the file." << endl; } return 0; } By Leweyehu Y.
Example 3: Writing data from an array to a file #include <iostream> #include <fstream> using namespace std; int main() { ofstream outputFile("output.txt"); if (outputFile.is_open()) { int data[] = {10, 20, 30, 40, 50}; for (int i = 0; i < 5; ++i) { outputFile << data[i] << " "; } outputFile.close(); cout << "Data written to the file successfully." << endl; } else { cout << "Failed to open the file." << endl; } return 0;} By Leweyehu Y.
A character can be written onto a file using the put()function. #include< fstream > int main() { char c; ofstream outfile ; outfile.open (“c:\\test.txt”, ios ::out); if( outfile.fail ()) { cerr << “\ nError opening test.txt”; exit(1); } for( int i =1;i<=15;i++) { cout << “\ nEnter a character : ”; cin >>c; outfile.put (c); } output.close (); }//end main By Leweyehu Y.
Closing a file When we are finished with our input and output operations on a file we shall close it so that its resources become available again. In order to do that we have to call the stream's member function close(). myfile.close (); Once this member function is called, the stream object can be used to open another file, and the file is available again to be opened by other processes. By Leweyehu Y.
#include < iostream > #include < fstream > using namespacestd ; int main () { ofstream myfile ("example.txt"); if( myfile.is_open ()) { myfile << "This is a line.\n"; myfile << "This is another line.\n"; myfile.close (); } else cout << "Unable to open file"; return 0; } By Leweyehu Y.
Reading a file #include<iostream> #include<fstream> using namespace std; int main() { ifstream input; char s; input.open("kal.txt",ios::out|ios::in); if(input.is_open()) { input>>s; cout<<s; } input.close(); } By Leweyehu Y.
Reading the file line by line #include <iostream> #include <fstream> #include <string> int main() { ifstream inputFile("input.txt"); if (inputFile.is_open()) { string line; while (getline(inputFile, line)) { cout << line << std::endl; } inputFile.close(); } else { cout << "Failed to open the file." << endl; } return 0;} By Leweyehu Y.
#include < iostream > #include < fstream > #include <string> using namespacestd ; int main () { string line; ifstream myfile ("example.txt"); if( myfile.is_open ()) { while(! myfile.eof () ) { getline ( myfile,line ); cout << line << endl ; } myfile.close (); } elsecout << "Unable to open file"; return 0; } By Leweyehu Y.
Types of files To write data to a sequential file in C++, you can use the std::ofstream class along with the stream insertion operator (<<). An example that demonstrates how to write data to a sequential file: int main() { ofstream outputFile("output.txt"); if (outputFile.is_open()) { outputFile << "Hello, World!" << endl; outputFile << 42 << endl; outputFile << 3.14159 << endl; outputFile.close(); cout << "Data written to the file successfully." << endl; } else { cout << "Failed to open the file." << endl; }return 0;} By Leweyehu Y.
Read data from a sequential file To read data from a sequential file in C++, you can use the std::ifstream class along with the extraction operator (>>). Here's an example that demonstrates how to read data from a sequential file: By Leweyehu Y.
#include <string> int main() { ifstream inputFile("input.txt"); if (inputFile.is_open()) { string line; int number; double value; while (getline(inputFile, line)) { std::cout << "Read line: " << line << endl; } inputFile.close(); cout << "Data read from the file successfully." << endl; } else { cout << "Failed to open the file." << endl; } return 0; } By Leweyehu Y.
Opening Random_access file By Leweyehu Y.
Writting random access ofstream out; out.open("zinash.txt",ios::out|ios::app|ios::binary); if(out.fail()) { cerr<<"file not opened\n"; exit(1); } int x; cout<<"enter the number\n"; cin>>x; out.write((char*) &x,sizeof(x)); out.close(); cout<<"data has been saved”<<endl; By Leweyehu Y.
Reading random-access ifstream in;int x; in.open("zinash.txt",ios::in|ios::app|ios::binary); if(in.fail()) { cerr<<"file not opened\n"; exit(1); } while(in.read((char*) &x,sizeof(x))); cout<<x<<endl; in.close(); return 0; } By Leweyehu Y.