Can't get Sams example to work (re-opening file)

A

Arfur Million

Hello, I hope it's OK to post beginner's questions to this group? If not,
please direct me to the right one.

I'm having trouble with the following program, which is taken from SAMS
Teach Yourself C++ in 21 Days. The idea is that an existing text file is
displayed to the user, who is prompted for text to append to the file. The
file with its new contents should then be displayed to the screen.

Everything works except the fin.open(fileName) statement, instead the error
branch is taken. Hence the contents of the file are not re-displayed to the
screen (true even if I remove the return(1) as you'd expect).

If I remove the block of code that displays the original contents then I
don't get a problem (I've marked this block with //START and //END).
Anyway, here's the code. I've removed the bit that does the append, since I
get the same results with or without it:

//Sams 17.17
#include <fstream>
#include <iostream>
using namespace std ;

main()
{
char fileName[50] ;
char buffer[255] ;
cout << "Please re-enter the file name : " ;
cin >> fileName ;
ifstream fin(fileName) ;
//START
if (fin) //test for existence
{
cout << "Current file contents : \n" ;
char ch ;
while (fin.get(ch))
cout << ch ;
cout << "\n* End of file * \n" ;
}
//END
fin.close() ;

fin.open(fileName) ; //This fails!
if (fin.fail()) //Same as if(!fin)
{
cout << "\nUnable 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 *\n" ;
fin.close() ;
return(0) ;
}

I'm using the g++ version 3.2 compiler under Linux 2.4-18. Thanks for
pointing out any silly mistakes I've made!

Arfur
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top