-1

I'm having troubles with insertion of text, in append, in a classical text file. What I want to do is simple : insert a single character in front of some lines. I know the exact offset of each line beginning. I have one restriction, I have to use the Windows API : CreateFile(), WriteFile(), SetFilePointer()...

I can't insert text, whatever I do, the program write to the end, or if it writes at the good offset, it erase the existing text.

Here is my code (I just simplified some checks to be more readable here) :

HANDLE handleFile = CreateFile (filename,
                                FILE_APPEND_DATA,
                                FILE_SHARE_READ, //SHARE
                                NULL, //SecurityAttibute
                                OPEN_ALWAYS,
                                FILE_ATTRIBUTE_NORMAL,
                                NULL);

if (handleFile != INVALID_HANDLE_VALUE) {
    if (SetFilePointer (handleFile, 12345, NULL, FILE_BEGIN) != INVALID_SET_FILE_POINTER) {
          DWORD written = 0;
          WriteFile (handleFile, "$", 1, &written, NULL);
    }
}

When I use FILE_APPEND_DATA, the SetFilePointer() doesn't work and my character is written to the end.

When I use GENERIC_WRITE, or even FILE_GENERIC_WRITE, the character is written at the good offset, but it erase the present character :'(

What is the good parameter to really insert please ?

PS : this code is for very large files, so read / write the whole file is not possible, it would be too long.

Thanks a lot !

Katsudon
  • 11
  • 1
  • Why is the read/write option not possible? You could buffer/stream it in sections? – Rowland Shaw Jan 25 '16 at 16:59
  • The program I am writing is handling large text files, kind of database (not my choice !). This character in the front is here to tag the line as "deleted". The next complete load will ignore those lines. – Katsudon Jan 25 '16 at 17:14

1 Answers1

2

You cannot insert text into a file in the way you are attempting. You can append data to the end, or you can overwrite existing data. In order to effect an insertion you have to re-write all the contents that follow the point of insertion.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • It's so bad ! So I have no other solution, I will rewrite the content following my insertion.... Thank you ! – Katsudon Jan 25 '16 at 17:12