How to append to txt-file?

 

Hello all,

I'm trying to create some report by means of mq5 and cannot find the way to append to existing text file.

The idea is, that once file created and some line(s) have been written to it,
every additional lines must be added (appended) to this existing file,
irrespective - how many times I would re-start MT5 or change the EA parameters.

Acoording to "file opening flags" documentation
(found here https://www.mql5.com/en/docs/constants/io_constants/fileflags)
combination of these 2 flags FILE_READ|FILE_WRITE should work,
however - it is not.

Not sure, where the problem is - I've tried lots of combinations of the file opening flags
without much luck: it is over-writing the file every time I re-start MT5
and only one last line exists there, like this
001 2011.02.22 08:21:56 init() OK

I would like to see several lines, like this (assuming - I'm re-starting MT5 every minute at 56 sec):
001 2011.02.22 08:21:56 init() OK
001 2011.02.22 08:20:56 init() OK
001 2011.02.22 08:19:56 init() OK


Is it possible to pre-serve the file content in MT5 and just append to it?

My sample code is pretty simple:

// this is sample of working with file

string file_name     = "Combined_Report.txt";
int file_handle = -1;

int OnInit() {

        // ...

        file_handle = FileOpen(file_name, FILE_READ|FILE_WRITE|FILE_TXT);
        if (file_handle <= 0) {
                Print("Error opening rep-file: " + file_name);
        }


        if ( file_handle > 0 ) {
                FileWrite(file_handle, "001 " + TimeToString(TimeCurrent(), TIME_DATE|TIME_SECONDS) + " init() OK");
                FileFlush(file_handle);
        }


}


 

 

Documentation on MQL5: Standard Constants, Enumerations and Structures / Input/Output Constants / File Opening Flags
  • www.mql5.com
Standard Constants, Enumerations and Structures / Input/Output Constants / File Opening Flags - Documentation on MQL5
 

You should use FileSeek to move position of the file pointer to the end of file.

void OnStart()
  {
   string file_name= "Combined_Report.txt";
   int file_handle = -1;
   file_handle=FileOpen(file_name,FILE_READ|FILE_WRITE|FILE_TXT);
   if(file_handle==INVALID_HANDLE)
      Print("Error opening rep-file: "+file_name);
//---
   FileSeek(file_handle,0,SEEK_END);
   FileWrite(file_handle,"001 "+TimeToString(TimeCurrent(),TIME_DATE|TIME_SECONDS)+" init() OK");
   FileFlush(file_handle);
   FileClose(file_handle);
  }
Documentation on MQL5: File Functions / FileSeek
  • www.mql5.com
File Functions / FileSeek - Documentation on MQL5
 

Thank you, Alexvd for prompt reply!

It's working!

 

 

Reason: