Various ways to read from a file
#include <iostream>
#include <fstream>
using namespace std;
// dumps file to screen
int main()
{
string line,word;
ifstream f("mydata.txt");
//ifstream f;
//f.open("mydata.txt", ios::in);
cout<<"----------reading by line -----------------------"<<endl;
//ex #1
while ( getline(f,line) ) //line delimeted
{
cout<<line<<endl;
}
//f.close();
//f.open("mydata.txt", ios::in);
f.clear(); // clear eof state flag from true to false
//f.seekg(0); // set seek get file pointer to beginning of file
//f.seekg(0,ios::beg);
f.seekg(0,f.beg); //resets file pointer back to the top
cout<<"----------reading by words-----------------------"<<endl;
//ex #2
while ( f >> word ) //space delimited
{
cout<<word<<endl;
}
f.clear();
f.seekg(0,ios::beg); //set seek get file pointer with offset, so 0 offset from beginning of file
cout<<"-----------reading by line but using eof() or good()----------------------"<<endl;
//ex #3
//while ( !f.eof() )
while ( f.good() )
{
getline(f,line); //use with !f.eof()
cout<<line<<endl;
}
cout<<"-----------reading by character-----------------------"<<endl;
f.clear();
f.seekg(0,ios::beg); //set seek get file pointer with offset, so 0 offset from beginning of file
//ex #4
char c;
while ( f.get(c) )
{
cout<<c;
}
f.close();
return 0;
}
Reading and Writing from a file
#include <iostream>
#include <fstream> // ofstream ifstream
#include <vector>
#include <algorithm> //sort
using namespace std;
//reads mydata.txt into a vector. Sorts the vector alphabetically then
//writes sorted vector to newdata.txt
int main()
{
string line;
vector <string> list;
//ifstream("mydata.txt");
ifstream inf;
inf.open("mydata.txt", ios::in); //reading
while ( getline(inf,line) )
{
list.push_back(line);
}
inf.close();
sort(list.begin(),list.end());
ofstream outf;
outf.open("newdata.txt", ios::out); //writing- warning this overwrites
for (unsigned int x=0; x<list.size(); x++)
{
outf << list[x] << endl;
}
outf.close();
return 0;
}
Read then custom sort based on age and write using pairs
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
//sort mydata people by age
bool mycomp(pair <string, int> x, pair <string, int> y){
return (x.second < y.second);
}
int main()
{
string name;
pair <string, int> p;
int age;
//use C++ pair
vector < pair<string, int> > pv;
ifstream inf;
inf.open("mydata.txt", ios::in);
while ( inf >> name && inf >> age) //extraction operator >> (space or newline delimeted)
{
p.first=name;
p.second=age;
pv.push_back(p);
}
inf.close();
sort(pv.begin(),pv.end(), mycomp);
ofstream outf;
outf.open("newdata.txt", ios::out);
for (unsigned int x=0; x<pv.size(); x++)
{
outf << pv[x].first << " " << pv[x].second << "\n";
//cout << pv[x].first << " " << pv[x].second << "\n";
}
outf.close();
return 0;
}