Professional Documents
Culture Documents
File Handling in C++ Module Name: Computer Programming Module Code: CSE 1018Y
File Handling in C++ Module Name: Computer Programming Module Code: CSE 1018Y
Introduction to files
To be stored on secondary storage devices, data are written in
files.
To use files, our programs need to have the statement
#include <fstream>
If the file will be used for Input, our variable will be of type
ifstream
Eg.
ifstream in1;
Next, the file has to be opened - Here we also give the actual
name that the file has on the hard disk.
in1.open("file1.txt");
Introduction to files
ifstream objects (variables) are simply specialized kinds of
input stream objects.
They can perform all the same kinds of operations as done by the
special cin input stream, i.e. they can "give" values to integers,
characters, doubles, etc.
But, in addition, they have extra capabilities like being able to "open"
and "close" files.
Condition states
The iostream objects maintain flags that report on the state of
your input and output.The flags can be check using the
following boolean functions
eof()-returns true if the iostream objects has encountered end
of file.
bad()- returns true if you attempt an illegal operation.
fail()- returns true anytime an operation fails
good()- returns true when the above flags return false.
#include <iostream.h>
#include <fstream>
#include <fstream.h>
void main()
void main()
{ int x,y,z;
{ int x,y,z;
ifstream f(input.txt");
ofstream f("output.txt");
f>>x>>y>>z;
cout<<"x = "<<x<<endl;
cin>>x>>y>>z;
cout<<"y="<<y<<endl;
cout<<"z="<<z<<endl;
endl;
f.close();
f.close();
}
}
ifstream f1("test.txt");
cout<<"Here the content of the
file"<<endl;
char ch;
while (f1.get(ch))
cout << ch;
cout<<"\n **End of line
content***\n";
f1.close();
}
10
Open behaviors
The default behavior upon opening a file is to create the
file if it doesnt exist and to delete all its contents if the file
exists. The following allows you to change the default
behavior
ios::app-appends to the end of existing files rather than truncating
them
ios::ate-places you at the end of file, but you can write data
anywhere in the file
Ios::trunc- default choice, delete the content
Ios::nocreate- if the file does not exist, will not create the file thus
operation fails
Ios::no replace- if the file already exist, open fails.
11
cin.getline(buffer,255);
f<<buffer<<"\n";
f.close();
ifstream f1(fileName);
cout<<"Here the content of the
file"<<endl;
char ch;
while (f1.get(ch))
cout << ch;
cout<<"\n **End of line content***\n";
f1.close();
}
12