As I understood it's better to use fstream instead of fstream.h. When I
was porting my code (i'm using VC6.0++) i needed to let go of such
things as ios::noreplace and ios::nocreate. I neede to check if file
exists before creating it. If it exists we prompt that we are
overwriting. The files ar being passed in as command line arguments.
I did it like that:
#include <fstream>
std::fstream outFile;
....
....
....
outFile.open(ar gv[2],std::ios_base: :in);// the second argument is the
output file
if (! outFile)
{//file does not exist
outFile.open(ar gv[2],std::ios::out) ;
cout<<"Testing. ..";
}
else
{
cout<<"Warning: Output file already exists!\n";//prompt that it
exists
outFile.close() ;//close it
outFile.open(ar gv[2],std::ios::out) ; //open it for output
cout<<"Testing. ..";
}
outFile.close() ;
but this stuff didn't work if the file did not exist. It just created
an empty file;
I changed it like this:
std::ifstream tmpFile;
std::ofstream outFile;
....
....
tmpFile.open(ar gv[2],std::ios_base: :in);
if (!tmpFile)
{
outFile.open(ar gv[2],std::ios_base: :out);
cout<<"Testing. ..";
}
else
{
cout<<"Warning: Output file already exists!\n";
tmpFile.close() ;
outFile.open(ar gv[2],std::ios_base: :out);
cout<<"Testing. ..";
}
outFile.close() ;
this stuff works fine, but i would like to get rid of the tmpFile (if
possible).
Any ideas? Why didn' t the first one work?
was porting my code (i'm using VC6.0++) i needed to let go of such
things as ios::noreplace and ios::nocreate. I neede to check if file
exists before creating it. If it exists we prompt that we are
overwriting. The files ar being passed in as command line arguments.
I did it like that:
#include <fstream>
std::fstream outFile;
....
....
....
outFile.open(ar gv[2],std::ios_base: :in);// the second argument is the
output file
if (! outFile)
{//file does not exist
outFile.open(ar gv[2],std::ios::out) ;
cout<<"Testing. ..";
}
else
{
cout<<"Warning: Output file already exists!\n";//prompt that it
exists
outFile.close() ;//close it
outFile.open(ar gv[2],std::ios::out) ; //open it for output
cout<<"Testing. ..";
}
outFile.close() ;
but this stuff didn't work if the file did not exist. It just created
an empty file;
I changed it like this:
std::ifstream tmpFile;
std::ofstream outFile;
....
....
tmpFile.open(ar gv[2],std::ios_base: :in);
if (!tmpFile)
{
outFile.open(ar gv[2],std::ios_base: :out);
cout<<"Testing. ..";
}
else
{
cout<<"Warning: Output file already exists!\n";
tmpFile.close() ;
outFile.open(ar gv[2],std::ios_base: :out);
cout<<"Testing. ..";
}
outFile.close() ;
this stuff works fine, but i would like to get rid of the tmpFile (if
possible).
Any ideas? Why didn' t the first one work?
Comment