open file to append

Back to topics list To post a new topic, please log in or register
avatar
38
collierab 2010.08.25 03:08
 

hi,

i am writing up a log file from an EA. if the EA is restarted i want it to carry on writing to the same file... but append to the end of the file. initially this did not work for me, so i searched the forum and found https://forum.mql4.com/13774. i applied the directions there and my init() function now looks like:

void init() 
{
   fd = FileOpen(filename, FILE_WRITE|FILE_CSV);
   if (fd < 0) {
      Alert("open ", filename, " failed");
      FormatError();
      return;
   }
   
   if(FileSeek(fd, 0, SEEK_END)) {
      Print("appending to file");
   }
}

when the code starts the file descriptor is shifted to the end (i get "appending to file" in the experts log, so i gather that FileSeek() was successful). but the original file is overwritten. it is quite infuriating that something so simple is presenting such an obstacle! please can somebody tell me what (silly thing) i am doing wrong? thanks!

best regards, andrew.

 
avatar
539
Viffer 2010.08.25 03:25 #
 

You need file read and file write. file write will just overwrite the existing contents so you need to read in too...

FileOpen(file_name,FILE_CSV|FILE_READ|FILE_WRITE,';');

hth

V

 
avatar
38
avatar
38
collierab 2010.08.25 03:44 #
 
is it true then that FileSeek() only works if the descriptor is open for reading too?
 
avatar
539
Viffer 2010.08.25 03:53 #
 

It reads the whole file in, seeks the end, appends your line and then writes the whole lot back overwriting the current contents of the file. If you haven't read in anything, there is no end to seek so your line gets written as the first line and then that then overwirtes the current file contents...it doesn't really append to the file, it appends to a temp dataset and then overwites the file.

V

edit: whether that is what technically happens, I'm not sure, but descriptively, that's how I understand the process.


 
avatar
2644
phy 2010.08.25 03:53 #
 

If FILE_WRITE does not combine with FILE_READ, a zero-length file will be opened. If even the file containd some data, they will be deleted. If there is a need to add data to an existing file, it must be opened using combination of FILE_READ | FILE_WRITE.

 
avatar
38
collierab 2010.08.25 19:04 #
 
hi phy and viffer, thanks for clarifying the situation!
avatar
2
beyond-mql 2016.07.20 15:44 #
 
the append works ok when using FileSeek() with FILE_READ | FILE_WRITE, but how about if you need to monitor the file from another application i.e. if you open the file with FILE_SHARE_READ | FILE_WRITE ?
avatar
2
beyond-mql 2016.07.20 15:56 #
 
ah yes, the mql genie... you need to use FILE_READ|FILE_SHARE_READ|FILE_WRITE, since FILE_SHARE_READ does not load the file... thanks genie ;-)
Back to topics list  

To add comments, please log in or register