Very strange file action
This snippet opens a file and inputs the number of records stored at the start; but then after that you will see I repeat the fstream allocation (without closing the original) and everything works exactly as it should.
However if I take this repeat fstream statement out it then doesn't output anything to the file - this I don't understand and it just doesn't seem right - is it - can anyone explain this to me?
fstream jcfile ( filename);
if ( !jcfile.is_open() )
cout<<endl<<endl<<endl<<"The file could not be opened.";
cout<<endl<<endl<<endl<<"There are currently "<<numrecords<<" records in this file.";
fstream jcfile (filename);// why is this needed
jcfile<<"hello you sailor";
Why do you think it's needed? I don't do a lot of C++ I/O, but it sounds like the stream may be entering a failed state after your initial read?
I know it is needed, I just don't know why.
The only way I found out it was needed was originally I used istream and ostream and opened each seperately, when I changed it to fstream so that I could read and write just to one instance that statement got left in the middle by mistake - originally with a close statement before it. I tried taking the close and reeopen stements out and it didn't work then I tried with just the open statement back in and it worked as wanted I just can't understand why.
Even stranger, I have now experimented a little and if that statement is not there and the file has no records it does not add a record but if the file exists and has say 2 records it correctly adds a third.
When I create the file for use I simply open a file and write the number '0' to it. I have now found that id I write a space after the '0' it works as expected without the second opening statement. Could it e that becaues the file only contains the number'0' it can't extend the file but by putting a space after iyt it can then extend the file a necessary - doesn't sound like normal behaviour but it fits with what is happening?
Why dont you just use ifstream or ofstream objects? And open them in the correct mode you require, what you have so far looks strange. See the FAQs
rags_to_riches' idea that the stream may be entering a failed state may have some merit. Try:
filename = filename + ".txt";
cout << endl << "\n\nThe file could not be opened.";
jcfile >> numrecords;
cout << endl << "\n\nThere are currently " << numrecords << " records in this file.";
jcfile.seekp(numrecords * 20);
jcfile << "hello you sailor";
jcfile << numrecords;
As usual you have come up with the right answer, it works with that statement in there - is there any way I can get a brain transplant from you?!