Good evening ladies and gents,
Had a question concerning this piece of code that I'm trying out from a book, it supposed to open a file, write text to it, close it, reopen it, append text to it and then write the text from the file to the console screen, it works fine up untill the text has to be written to the console screen, then I get the message that the file can't be opened for reading though the text is added to the file?
What am I doing wrong?
#include <fstream>
#include <iostream>
using namespace std;
int main() // returns 1 on error
{
char fileName[80];
char buffer[255]; // for user input.
cout << "Please reenter the file name: ";
cin >> fileName;
ifstream fin(fileName);
if (fin) // allready exists ?
{
cout << "Current file contents:\n";
char ch;
while (fin.get(ch))
cout << ch;
cout << "\n***End of file contents.***\n";
}
fin.close();
cout << "\nOpening " << fileName << " in append mode...\n";
ofstream fout(fileName, ios::app);
if (!fout)
{
cout << "Unable to open " << fileName << " for appending !\n";
return 1;
}
cout << "\nEnter text for this file: ";
cin.ignore(1, '\n');
cin.getline(buffer, 255);
fout << buffer << "\n";
fout.close();
fin.open(fileName); // reassign existing fin object.
if (!fin) // <-- problem is here.
{
cout << "Unable to open " << fileName << " for reading !\n";
return 1;
}
cout << "\nHere's the contents of the file: \n";
char ch;
while (fin.get(ch))
cout << ch;
cout << "\n***End of file contents.***\n";
fin.close();
return 0;
}