I'm following some exercises in a book to figure out how to work with files, and I thought I was doing pretty good... but for some reason I can't get my program to open a file.
The lesson is teaching me how to open a file in Append mode using ios:app. It seems to be working properly, as in it's appending the new information to the file and I can see it when I open the file, but it refuses to re-open the file within the program.
Here's the code:
C++ Code:
#include "stdafx.h"
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char fileName[80];
char buffer[255]; // for user input
cin >> fileName;
ifstream fin(fileName);
if (fin)
{
cout <<
"Current file contents:\n";
char ch;
while (fin.get(ch))
cout <<
"\n****END OF FILE****\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 the file: ";
cin.ignore(1,'n');
cin.getline(buffer,255);
fout << buffer << "\n";
fout.close();
fin.open(fileName); //reassign existing fin object
if (!fin)
{
cout <<
"Unable to open " << fileName <<
" for reading.\n";
system("pause");
return(1);
}
cout <<
"\nHere's the contents of the file: \n";
char ch;
while (fin.get(ch))
cout <<
"\n****END OF FILE****\n";
fin.close();
system("pause");
return 0;
}
First it opens the file using ifstream, and if the filename already exists it displays the file's contents (line 15-24).
Then, (line 26-40) it opens the file in append mode and lets the user put in a string of text. This is appended to the file correctly.
The problem comes in the next section, lines 42-55. Specifically on line 42. According to my book, I don't need to use ifstream. fin is already declared (back on line 15) so fin.open(fileName) should open up the file for reading.
But every time I try it, the "if (!fin)" loop is activated and I get the error message saying the file couldn't be opened and the program terminates.
(I added "system("PAUSE")" lines to keep the console box open so I could see the output. Not the best method, I know, but it's quick and easy.)
So why can't I reopen my file for reading? What's the problem here?