Download MetaTrader 5

rewrite a file partially ...?

To add comments, please log in or register
Carl Schreiber
7678
Carl Schreiber  

Hi

is there another way than to open a file to read, read it totally, close it, do some changes e.g. actualize the last access date of a line  and then reopen it again to write and rewrite it completely and close it.

I open this file read|write|binary (!), read it, place the file pointer at the beginning (FileSeek(hdl,0,SEEK_SET);), rewrite all the lines, close the file.

NOW in case something was changed so that one line has become a bit shorter after the last line written I found still some residuals - which means that I have to get rid of the the part from where the pointer is ( ulong where = FileTell(hdl); ) to the end.

But how can I delete these bytes in the file - except rewriting the whole file - is there a mt4 solution?

To explain it in pictures:

orig: File looks like:

key 001;lkjyhvlkjhkjfh;2017.07.07 21:09\n
key 001;lkjyhvlkjhkjfh;2017.07.07 21:09\n

changed content of the modified file looks like:

key a;lkjyhvlkjhkjfh;2017.07.07 21:09\n
key 001;lkjyhvlkjhkjfh;2017.07.07 21:09\n
09\n

Now I want to delete everything after : "... 2017.97.07 21:09\n" to the end of the file.

Is it possible to move the EndOfFile up a bit to get rid of the bytes this way?

This try failed as it doesn't move the file pointer so that byte it points to is not re-written by "" :(

      ulong where = FileTell(hdl);
      bool atEnd = FileIsEnding(hdl);
      while( !FileIsEnding(hdl)) {
         FileWriteString(hdl,"",0); // it doesn't write anything so the pointer isn't moved and FileIsEnding is never reached :(
         where = FileTell(hdl);
         atEnd = FileIsEnding(hdl);
         DebugBreak();
      }
      FileClose(hdl); 

(At least I tried it.)

I can only replace the existing bytes (characters) by e.g.  "\n" so the at these lines (StringLen(..)<5) are skipped).

Drazen Penic
2730
Drazen Penic  

No. You can't shorten the file by deleting few characters in the middle.

If you want to shorten the file, you need to manually rewrite from the position of the deleted characters to the end.

The simplest thing is to read the file, make modifications in memory and then save everything to the empty file. Can be done the way you want it, but it requires a bit more effort. 

To add comments, please log in or register