File Handling Notes
File Handling Notes
Binary file:- It is a file that contains information in the same format as it is held in memory. In binary
files, no delimiters are used for a line and no translations occur here.
int main()
{
ofstream myDB("DB.text");
myDB << "Writing to file using fstream constructor!" << endl;
myDB.close ();
return 0;
}
Opening File:
Opening file using constructor
ofstream outFile("sample.txt"); //output only
ifstream inFile(“sample.txt”); //input only
Opening File Using open ()
StreamObject.open(“filename”, [mode]);
ofstream outFile;
outFile.open("sample.txt");
ifstream inFile; inFile.open("sample.txt");
function open():
fstream file;
file.open ("example.dat", ios::out | ios::app | ios::binary);
Closing File:
outFile.close();
inFile.close();
Example:
// io/read-file-sum.cpp - Read integers from file and print sum.
// Fred Swartz 2003-08-20
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
int main() {
int sum = 0;
int x;
ifstream inFile;
inFile.open("test.txt");
if (!inFile) {
cout << "Unable to open file";
exit(1); // terminate with error
}
while (inFile >> x) {
sum = sum + x;
}
inFile.close();
cout << "Sum = " << sum << endl;
return 0;
}
File Mode:
Files Explanation
MODES
ios::in Input mode – Default mode with ifstream and files can be read only
ios::out Output mode- Default with ofstream and files can be write only
ios::binary Open file as binary
ios::app Preserve previous contents and write data at the end ( move forward only)
ios::ate Preserve previous contents and write data at the end.( can move forward and
backward )
ios::trunc If the file already exists, all the data will lost.
ios::noreplace Open fails if the file already exist
ios::nocreate The file must already exist. If file doesn't exist, it will not create new file
Read from a text file and than write in another text file
#include<fstream.h>
void main()
{
ofstream fout(“sare1.txt”); //create a file to write
ifstream fin(“sare1.txt”);
fout<<“Hello….!!”;
fout.close(); //closing the file
fout.open(“sare2.txt”); //create file to write
char ch;
while(fin) //loop wiill run till end of file
{
fin>>ch; //reading data from file
fout<<ch; //writing data to file
}
fin.close();
fout.close();
}
/*you can see the file sare2 in your BIN
folder containg data same as of file sare1*/
myFile.close();
}