Search code examples
mql4

MQL4 error 5004 and 5002 when try to read file


I'm coding in MQL4 to read a file. When I just define the filename and put the file in specified place it shown error 5004. But when I define the path it shown 5002. I've been to MetaTrader forum and found this (https://www.mql5.com/en/forum/7049) thread. But still not solve. Did I miss something here?

string filename = TerminalInfoString(TERMINAL_DATA_PATH)+"\\MQL4\\Files\\output.txt";
   Print(filename);
   ResetLastError();
   int file_handle=FileOpen("out.txt", FILE_READ|FILE_TXT);
   //int file_handle=FileOpen(filename, FILE_TXT|FILE_READ);
   //Print(file_handle);
   string up, down, sideway;
   up = down = sideway = 0;
   if (file_handle!=INVALID_HANDLE){
      Print("read");
      up=FileReadString(file_handle);
      down = FileReadString(file_handle);
      sideway = FileReadString(file_handle);
   } else{
      Print("file open error: ", GetLastError());
   } FileClose(file_handle);

Solution

  • int file_handle=FileOpen("out.txt", FILE_READ|FILE_TXT); means that you have your file "out.txt" in your folder, e.g. C:\Users\User1\AppData\Roaming\MetaQuotes\Terminal\999999DEA9630EA94D0715D755974F1D\MQL4\Files\out.txt. If you try in tester, the path is C:\Users\User1\AppData\Roaming\MetaQuotes\Terminal\999999DEA9630EA94D0715D755974F1D\tester\files\out.txt Make sure you have the file there to solve the 5002 error. It might happen that you successfully opened the file once but failed to close when wrote the code. and you cannot open it now. One way is to close MT4 (and it will close all open files), another way is to open files in SHARE mode. int file_handle=FileOpen("out.txt", FILE_READ|FILE_SHARE_READ|FILE_TXT);