File
File
Streams
stream - a sequence of characters interactive (iostream)
•cin - input stream associated with keyboard.
• cout - output stream associated with display file (fstream)
•ifstream - defines new input stream (normally associated with a
file).
•ofstream - defines new output stream (normally associated with a
file).
-------------------------------------------------------------------------------------------------------
Dr. Omaima Bahaidara ………………. 1 ………..………. Computer Programming
Streams
C++ streams
-------------------------------------------------------------------------------------------------------
Dr. Omaima Bahaidara ………………. 2 ………..………. Computer Programming
Open() Function
Opening a file associates a file stream variable declared in the
program with a physical file at the source, such as a disk.
In the case of an input file:
o the file must exist before the open statement executes.
o If the file does not exist, the open statement fails and the
input stream enters the fail state
An output file does not have to exist before it is opened;
o if the output file does not exist, the computer prepares an
empty file for output.
o If the designated output file already exists, by default, the
old contents are erased when the file is opened.
Open() Function
Example : fout.eof( );
-------------------------------------------------------------------------------------------------------
Dr. Omaima Bahaidara ………………. 3 ………..………. Computer Programming
Example1: Opening and Closing
#include <fstream> int main ()
{
ifstream fsIn; //input
ofstream fsOut; // output //Open the files
fsIn.open("prog1.txt"); //open the input file
fsOut.open("prog2.txt"); //open the output
//Code for data manipulation
//Close files
fsIn.close();
fsOut.close();
return 0;
}
-------------------------------------------------------------------------------------------------------
Dr. Omaima Bahaidara ………………. 4 ………..………. Computer Programming
Example3: Reading from a file
// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string line1;
ifstream myfile;
myfile.open("example.txt");
if (myfile.is_open()) {
while (getline(myfile, line1)) {
cout << line1 << '\n'; }
myfile.close();
}
else
cout << "Unable to open file"<< endl;
system("pause");
return 0;
}
-------------------------------------------------------------------------------------------------------
Dr. Omaima Bahaidara ………………. 5 ………..………. Computer Programming