Fixed problem where file handles could possible stay open

This commit is contained in:
Pavol Marko 2004-10-03 16:55:12 +00:00
parent 605ca152c2
commit 981f41aee0

View File

@ -57,6 +57,23 @@
CVector<FILE *> FileList; CVector<FILE *> FileList;
class AutoFilePtr
{
FILE *m_FP;
public:
AutoFilePtr(FILE *fp) : m_FP(fp)
{ }
~AutoFilePtr()
{
if (m_FP)
fclose(m_FP);
}
operator FILE* ()
{
return m_FP;
}
};
static cell AMX_NATIVE_CALL read_dir(AMX *amx, cell *params) static cell AMX_NATIVE_CALL read_dir(AMX *amx, cell *params)
{ {
#ifdef __GNUC__ #ifdef __GNUC__
@ -230,17 +247,20 @@ static cell AMX_NATIVE_CALL file_size(AMX *amx, cell *params) /* 1 param */
{ {
int iLen; int iLen;
char* sFile = get_amxstring(amx,params[1],0,iLen); char* sFile = get_amxstring(amx,params[1],0,iLen);
FILE* fp = fopen(build_pathname("%s",sFile),"r"); AutoFilePtr fp(fopen(build_pathname("%s",sFile),"r"));
if ( fp != NULL) { if ( fp != NULL)
if ( params[0] < 2 || params[2] == 0 ){ {
if ( params[0] < 2 || params[2] == 0 )
{
fseek(fp,0,SEEK_END); fseek(fp,0,SEEK_END);
int size = ftell(fp); int size = ftell(fp);
fclose(fp);
return size; return size;
} }
else if ( params[2] == 1 ){ else if ( params[2] == 1 )
{
int a = 0,lines = 0; int a = 0,lines = 0;
while( a != EOF ){ while( a != EOF )
{
++lines; ++lines;
while ( (a = fgetc(fp)) != '\n' && a != EOF ) while ( (a = fgetc(fp)) != '\n' && a != EOF )
; ;
@ -454,7 +474,7 @@ static cell AMX_NATIVE_CALL amx_filesize(AMX *amx, cell *params)
int len; int len;
char *file = build_pathname("%s", format_amxstring(amx, params, 1, len)); char *file = build_pathname("%s", format_amxstring(amx, params, 1, len));
long size; long size;
FILE *fp = fopen(file, "rb"); AutoFilePtr fp(fopen(file, "rb"));
if (fp) { if (fp) {
fseek(fp, 0, SEEK_END); fseek(fp, 0, SEEK_END);
size = ftell(fp); size = ftell(fp);