In a project that I have downloaded from net I found a class which should provide auto open and auto close of file. There are some points which are not clear to me, maybe you can explain?
type definition
http://paste.ofcode.org/BiYFiEGysER7FHFX25FPMy
header file
http://paste.ofcode.org/B6PSp3XTrCLw5q59vpysFD
The definition:
http://paste.ofcode.org/qgBVD47qeTN7NYywA7Dw5X
I would like to know what is the type FILE for. I know that it is pointer, but don't understand why the class needs it. How does the class initiate the data into _file? I see get() only returns the _file. Now I see that _file is also a function... _file(fopen(filename, mode)) ... So is this some special case when the _file variable is filled with a content from the result in the argument _file(..) function because it has same name like the variable?
Also AutoFile constructor seems to be empty, so how the function _file is called? Looks it must be auto.
The AutoFile is used like so:
type definition
Code:
#ifndef _FILE_DEFINED
struct _iobuf {
char *_ptr;
int _cnt;
char *_base;
int _flag;
int _file;
int _charbuf;
int _bufsiz;
char *_tmpfname;
};
typedef struct _iobuf FILE;
#define _FILE_DEFINED
#endif
typedef struct _iobuf FILE;
header file
Code:
// @return the file's size, in bytes.
long fsize(const char *path); // TODO: take a FILE*
// AutoFile closes file - see utilio.cpp for definition
class AutoFile
{
public:
AutoFile(FILE * file);
AutoFile(const char * filename, const char * mode);
~AutoFile();
FILE * get();
void close(); // Close the file. Further calls to get() will return NULL.
private:
AutoFile(const AutoFile&); // no copy constructor!
FILE * _file;
};
inline FILE * AutoFile::get()
{
return _file;
}
The definition:
Code:
long fsize(const char *path)
{
AutoFile file(path, "rb");
fseek(file.get(), 0, SEEK_END);
return ftell(file.get());
// AutoFile closes file
}
AutoFile::AutoFile(const char * filename, const char * mode)
: _file(fopen(filename, mode))
{
if (!_file)
throw io_error("Could not open file.");
}
void AutoFile::close()
{
if (_file)
fclose(_file);
}
AutoFile::~AutoFile()
{
close();
}
AutoFile::AutoFile(const AutoFile &)
{
// never called
}
I would like to know what is the type FILE for. I know that it is pointer, but don't understand why the class needs it. How does the class initiate the data into _file? I see get() only returns the _file. Now I see that _file is also a function... _file(fopen(filename, mode)) ... So is this some special case when the _file variable is filled with a content from the result in the argument _file(..) function because it has same name like the variable?
Also AutoFile constructor seems to be empty, so how the function _file is called? Looks it must be auto.
The AutoFile is used like so:
Code:
AutoFile tempout(dpath, "wb");
AutoFile scx(path, "wb");
AutoFile temp(dpath, "rb");
AutoFile dc2in(path, "rb");
AutoFile textout(path, "w");
Last edited: