48 Lecture 15 - (File Handling)
48 Lecture 15 - (File Handling)
int main()
{
string numfile = "numbers.txt";
ofstream ofile;
ofile.open(numfile.c_str());
//if (!ofile)
int j=0
while(j<10)
{
ofile << j << " " << rand()%850+150 << endl;
j = j + 1;
}
ofile.close();
return 0;
}
File reading example
#include <iostream>
#include <fstream>
return 0;
}
Reading/writing in different files
#include <iostream> char c;
#include <fstream> ifile >> c;
//c = ifile.get();
using namespace std; while(!ifile.eof())
{
int main() if(c >= 'a' && c <= 'z')
{ {
string infile; c = c-'a'+'A';
cout << "Enter input file name "; }
cin >> infile; ofile << c;
ifile >> c;
string outfile; //c = ifile.get();
cout << "Enter output file name "; }
cin >> outfile;
ifile.close();
ifstream ifile(infile.c_str()); ofile.close();
//if (!ifile)
ofstream ofile(outfile.c_str()); return 0;
//if (!ofile) }
https://en.wikipedia.org/wiki/Netpbm_format
File handling functions
• Every iostream functionality may be used
with files, some commonly used functions
for data manipulation are:
• put() and get(), getline(), ignore(), peek(), etc.
• io manipulators like endl, setw(), etc.
• read() and write() for binary data.
• Besides data manipulation, some of the
functions are available for testing the state of
the stream, e.g.,
• good(), is_open(), eof(), clear(), etc.
More file handling functions
File open modes
If more than one
mode/flag is required,
character | has to be in
between
e.g. ios::in | ios::out | ios::ate
Random Access
To be continued . . .