Professional Documents
Culture Documents
Basics On File: Aiub. Spring 2018
Basics On File: Aiub. Spring 2018
Basics On File: Aiub. Spring 2018
Files are text files in which can be created and manipulated (writing, reading, editing) using c++ file streams.
¡ ofstream: Stream class to write on files.
¡ ifstream: Stream class to read from files.
¡ fstream: Stream class to both read and write from/to files.
return 0;
}
© Dr. Mahbubul Syeed, Associate Prof., AIUB
#include<iostream>
FILES IN C++: READING INTEGERS FROM A FILE
#include<string>
#include<fstream> // library for file input output
using namespace std;
int main()
{ // opening a input stream over the file
ifstream fin("firstFile.txt");
int x; 5
7
// if file is successfully open then 11
if (fin.is_open()) 13
{
19
while(1)
{
fin>>x;
if(fin.eof()) break; // Checks if it’s an end of the file
cout<<x<<endl;
}
fin.close();
}
else
cout << "File does not exists!!" << endl;
return 0;
}
© Dr. Mahbubul Syeed, Associate Prof., AIUB
#include<iostream>
FILES IN C++: READING CHARACTERS FROM A FILE
#include<string>
#include<fstream> // library for file input output
using namespace std;
int main()
{ // opening a input stream over the file
I
ifstream fin("firstFile.txt"); L
char x; o
v
In a file firstFile.txt you have following text
// if file is successfully open then e
I Love programming
if (fin.is_open())
p
{
r
while(1)
o
{
fin>>x;
g
if(fin.eof()) break; // Checks if it’s an end of the file r
cout<<x<<endl; a
} m
fin.close(); m
} i
else
n
cout << "File does not exists!!" << endl;
g
return 0;
}
© Dr. Mahbubul Syeed, Associate Prof., AIUB
WRITING PROGRAMS
int main(){
// opening file in input mode to read char
ifstream fin("alphabet.txt");
//open two more file to store vowel and consonent respectively
ofstream fvowOut("vowel.txt");
ofstream fconsonentOut("consonent.txt");
if(x == 'a' || x == 'e' ||x == 'i' ||x == 'o' ||x == 'u' || x == 'A' || x == 'E' ||x == 'I' ||x == 'O' ||x == 'U’)
fvowOut << x;
else
fconsonentOut << x;
}
fin.close();
fvowOut.close();
fconsonentOut.close();
}
else
cout << "File does not exists!!" << endl;
© Dr. Mahbubul Syeed, Associate Prof., AIUB
return 0;
}
OTHER CODES FOR PRACTICE
FILE
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 (good checks more state flags at once).