How to detect if file exists?

 

Hello,

I know that in a EA we can try to read a file using FileOpen(...) and get the error using GetLastError() to see if the file exist, but is there any other way to check if a file exist on the folder "experts/files"?

I have an EA that relies on files that it creates, however when the EA restarts it can be messed up by its own old files that it creates, and that happens after I close the MT4 without "telling" the EA to remove its useless old files.

for me it would just be easier to find out if old files exist or not without trying to open them all.

Thank you in advance.

 

Not Easy

You have identified the situation pretty accurately; I have been there as well. MT4's file handling capabilities are very basic. What we need is a FileExist() function, but instead we have to use FileOpen(). Somebody suggested on another forum writing a DLL containing all the file handling capabilities of Windows, but that seems to be a lot of effort for a one time requirement.

 
Maybe something like this (a possible "way around") :
//+------------------------------------------------------------------

//|

//+------------------------------------------------------------------

#import "kernel32.dll"

int _lclose (int);

int _lopen (string,int);

#import

#define HFILE_ERROR -1

//

//

//

//

//

bool fileExist(string searchName)

{

int fileHandle = _lopen(searchName,0);

if (fileHandle == HFILE_ERROR) return(false);

_lclose(fileHandle); return(true);

}

Possible problem is if the target file is exclusively opened at a time when you try to access it, but the good thing is that you are not limited to metatrader default folders. You can check any file

Attached a simple indicator that checks a file out of experts/files sub-folder

Files:
 

thank you

Thank you very much for both answers!

I'm running MT4 under Wine on Linux (opensuse) therefore using DLLs is not a viable option, I decide to solve the problem by enhancing my EA using some error detection code, based on the FileOpen() error return, basically the EA "decides" if the file exists or not (if it doesn't open is considered non-existent, and to be safe, the code tries to remove that file using FileDelete).

I'm Sorry for not being able to answer sooner, I was too busy.