Click to See Complete Forum and Search --> : Delete File associated with fstream
Lil'Hasher
March 6th, 2003, 09:35 AM
Hi,
In my program i have an fstream that creates a file "myfile.txt" in a directory. ie.
fstream file;
file.open("myfile.txt", ios:: out | ios::i n);
I was just wondering if there was anyway to delete that file "myfile.txt" from the directory within my program? I dont want it to exist after the program finishes executing.
PaulWendt
March 6th, 2003, 10:30 AM
I've done something similar. Are you familiar with the "Resource
Acquisition Is Initialization" programming paradigm? What it
basically means in C++ is that you acquire a resource as part of
an object's construction and you relinquish the resource as a part
of that objects destruction. So, what you can do is have a
wrapper class called TempFile or something like that. The
constructor of TempFile would open the file you need. TempFile
would also provide a method to get at the output file object; you
could even leave the ofstream object public if you wanted.
Then, the destructor of TempFile would delete the path referenced
by the oftream object [after closing it, of course].
Is this description adequate?
Lil'Hasher
March 6th, 2003, 10:46 AM
Hi Paul,
I think I understand what your saying, however i'm still unclear as to what the C++ syntax would be to do something like "destructor of TempFile would delete the path referenced
by the oftream object [after closing it, of course]." ie. what is the syntax to delete the path referenced by the ofstream?...I cant seem to find anything like that in the ofstream methods.
thanks
Mike Harnad
March 6th, 2003, 10:59 AM
How about using a plain old "remove()" function?
Bob Davis
March 6th, 2003, 12:16 PM
There may be a better way to do this.
Store the path of the filename in a std::string inside your TempFile class. Write your destructor like this:
// file = ofstream object
// fileName = file path
~Tempfile()
{
if (file.is_open()) file.close();
remove(fileName);
}
I don't know if there's a less-C way to do it, without using remove(), but that should do the job.
Andreas Masur
March 7th, 2003, 03:52 AM
Originally posted by Lil'Hasher
Hi Paul,
I think I understand what your saying, however i'm still unclear as to what the C++ syntax would be to do something like "destructor of TempFile would delete the path referenced
by the oftream object [after closing it, of course]." ie. what is the syntax to delete the path referenced by the ofstream?...I cant seem to find anything like that in the ofstream methods.
thanks
#include <fstream>
#include <string>
class CFoo
{
public:
CFoo(std::string strFile)
{
m_strFile = strFile;
// Open file
m_ofstrFile.open(m_strFile);
}
~CFoo()
{
// Close file
m_ofstrFile.close();
// Delete file
remove(m_strFile);
}
private:
std::string m_strFile;
std::ofstream m_ofstrFile;
};
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.