How to append to end of csv file ,starting from second last row ?

 
Hi,

I have the csv file format like below (to append  d2, e2 ,d3,e3 value) :

i have used  before FileSeek(handle,-2, SEEK_END) to append to end of file (in this case : d3,e3)  but I dont know what is the FileSeek (handle, ?, SEEK_END) to append the d2, e2 ,d3,e3 value. Please help.

a1, b1, c1, d1, e1 

a2, b2, c2, 

a3, b3, c3,

Regards
 

Don't double post! You already had another thread open.

          General rules and best pratices of the Forum. - General - MQL5 programming forum 2017.07.19
 
I have deleted the other 4 duplicated topics!
 
if (iTime(Symbol(),PERIOD_D1,0)!=PH10412U10) 
 {//5a 
 handle=FileOpen("Try.csv",FILE_CSV|FILE_READ|FILE_WRITE,',');
 FileSeek(handle, 0, SEEK_END); 
 FileWrite(handle,Symbol(),"a1","b1","c1"); 
 FileWrite(handle,Symbol(),"a2","b2","c2"); 
 FileClose(handle); 
 
 handle=FileOpen("Try.csv",FILE_CSV|FILE_READ|FILE_WRITE,',');
 FileSeek(handle,-2, SEEK_END); 
 FileWrite(handle," ","d1","e1","f1");
 FileWrite(handle," ","d2","e2","f2");
 FileClose(handle); 
 PH10412U10=iTime(Symbol(),PERIOD_D1,0);      
 }//7b 
 

I have tried to append d1,e1,f1 and d2,e2,f2 after c1 and c2 respectively but not successful. Please help.

 
chua le: Please help.
  1. I did — on one of your other (now deleted) topics. How rude to waste everyone's time.
  2. You have variable length fields and variable length lines. You can not seek back. Read the entire file into an array, update the array, rewind and rewrite the file.
 
Thanks. I thought there are different topics, that is why i post it differently, sorry for that.
 

You need to read through the file, thereby remembering the seek position of the previously read line. Once you've reached end of file condition, use that value to seek and rewrite from there.

More or less like this:

ulong lastpos=0;
ulong prevpos=0;
string lastA, lastB, lastC;
string prevA, prevB, prevC;

while(!FileIsEnding(handle))
  {
   prevpos=lastpos;
   prevA=lastA; prevB=lastB; prevC=lastC;
   lastpos=FileTell(handle);
   // read the whole line into lastA..C here
  }
FileSeek(handle,prevpos,SEEK_SET);
// write prevA..C plus additional values here
// write lastA..C etc here
 
Good thanks. Need to digest it first.
 
lippmaje:

Your code will not work because OP want to modify the second from the last line. Your code will destroy the last line.

chua le:

How to append to end of csv file ,starting from second last row ?

 

Thanks for reply,  is it confirmed  the code above will not work? Does it  mean the only way out is to use array to store value and  rewrite it once and for all?

 
William Roeder:

Your code will not work because OP want to modify the second from the last line. Your code will destroy the last line.

Yes of course, the remedy is to rewrite both lines (that's what the string variables prev... and last... are for). This is faster than to rewrite the whole file.
Reason: