Download MetaTrader 5

How to append to txt-file?

To add comments, please log in or register
rroz123 2011.02.22 10:44 

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
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");




Documentation on MQL5: Standard Constants, Enumerations and Structures / Input/Output Constants / File Opening Flags
Standard Constants, Enumerations and Structures / Input/Output Constants / File Opening Flags - Documentation on MQL5
Alexey Da
Alexey Da 2011.02.22 11:28  

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;
      Print("Error opening rep-file: "+file_name);
   FileWrite(file_handle,"001 "+TimeToString(TimeCurrent(),TIME_DATE|TIME_SECONDS)+" init() OK");
Documentation on MQL5: File Functions / FileSeek
File Functions / FileSeek - Documentation on MQL5
rroz123 2011.02.22 11:35  

Thank you, Alexvd for prompt reply!

It's working!



To add comments, please log in or register