what is its advantage over opening and closing? and also i think opening and closing helps sace memory?
I read about RAII, which is actually a very good practice. I was worried about memory consumption(even though it is small amounts).
I also have one question. If one uses new with RAII, is it still necessary to call delete?
There are many arguments why that is less than ideal.
When you use an fstream, you shouldn't thinking file. You ought to be thinking stream. You don't open/close streams. You just read/write them.
Like I said before, RAII. If you have an fstream, it should be in a usable and functional state from the start. There are a number of interlocking concepts that support robust design, such as Adam's exception guarantees. Being careless about state doesn't help.
I think it's just plain wrong to have a beginner's tutorial on fstreams that calls open/close on them. You'll be checking for EOF next It's not called the I/O stream library for nothing.
#include <fstream>
#include <vector>
#include <cstdio>
int main()
{
constchar* const file_name = "values.txt" ;
constchar* const backup_file_name = "values.txt.bak" ;
// read the values into a vector
std::vector<int> values ;
{
std::ifstream file(file_name) ; // open for input
int value ;
while( file >> value ) values.push_back(value) ;
}
// modify the values as needed
values.push_back(234) ;
values[0] = 1234567 ;
// etc.
// just to be safe, rename the old file to create a backup
std::rename( file_name, backup_file_name ) ;
// create the file afresh and write the modified values, one value per line
{
std::ofstream file(file_name) ; // create, and open for output
for( int v : values ) file << v << '\n' ;
}
// note: in this snippet, error checking has been elided for brevity
// if we have reached here with no errors, the backup may be deleted.
// std::remove( backup_file_name ) ;
}