Chitika

Thursday, October 20, 2011

C++: Perfectly file close on unexpected system shutdown

Logging utility need this fuctionality, for cases of forget to shutdown file or unhandled exceptions:

I created a class CLogFile, holding file descriptor and in destructor I close the file descriptor, initialize the default destructor to stderr:

class CLogFile {
private:

FILE *FileDescriptor;

public:
CLogFile(){
this->FileDescriptor=stderr;
}

~CLogFile(){
if(NULL != this->FileDescriptor &&
stdout != this->FileDescriptor &&
stderr != this->FileDescriptor) {
fclose(this->FileDescriptor);
FileDescriptor=stdout;
}
}

void SetFileDescriptorToFile(char *filename) {
if(NULL != this->FileDescriptor &&
stdout != this->FileDescriptor &&
stderr != this->FileDescriptor) {
fclose(this->FileDescriptor);
}

........

if((this->FileDescriptor=fopen(name, "a+")) == NULL) {
this->FileDescriptor=stderr;
throw "Can not open logfile";
}

........

}

FILE *GetFD() {

........

return this->FileDescriptor;

}

Now, File is opened through CLogFile object method call SetFileDescriptorToFile(filename) and method call GetFD() gives the file descriptor without worry about closing the file or for any unhandled exception.

No comments:

Post a Comment