I've found some similar posts on opening different files with the same file stream but they are difficult to understand. I'm trying to figure out for a larger project why I can't use the same file stream as in this example and what an alternative solution may be. And yes I am aware that this example opens the same file twice.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;ofstream thefile;
thefile.open ("example.txt");
thefile <<"writing this to a file. \n";
thefile.close();
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while (! myfile.eof())
{
getline (myfile, line);
cout << line << endl;
}
//myfile.close();
}
else cout << "unable to open file";
cout<<line;
cin>>line;//used only for a makeshift pause here
myfile.open ("example.txt");
if (myfile.is_open())
{
while (! myfile.eof())
{
getline (myfile, line);
cout << line << endl;
}
myfile.close();
}
else cout << "unable to open file";
return 0;
}
I'm using microsoft visual c++ 2010 express
vista 64 bit operating system
this bit of code is portions taken from a C++ language tutorial by Juan Soulie and slightly modified for this example.
Any help that would help me get an idea of how this doesn't work and a solution that would help me open multiple and diffent files would be greatly appreciated.