Append text at the end of a text file in win32 api

Ayse picture Ayse · Mar 29, 2013 · Viewed 9.3k times · Source

I am trying to open a text file, write some data into it and then append some more data at the end of the data already written to the file, but this doesnot work. Can anybody help me figuring out the problem with my code? CODE SNIPPET:

char buffer[]="Write this text to file";
DWORD dwWritten; // number of bytes written to file
HANDLE hFile;  

hFile=CreateFile("file.txt",GENERIC_READ|GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,0,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,0);
if(hFile==INVALID_HANDLE_VALUE)
  {
    MessageBox(0,"Could not create/open a file","Error",16);
    return 0;
  }
WriteFile(hFile,buffer,sizeof(buffer),&dwWritten,0);

DWORD dwPtr = SetFilePointer( hFile, dwWritten, NULL, FILE_END); //set pointer position to end file

WriteFile(hFile,buffer,sizeof(buffer),&dwPtr,NULL); 

CloseHandle(hFile);

Answer

singh picture singh · Mar 29, 2013

If you want to append data to a file you can use FILE_APPEND_DATA flag passing it to the CreateFile method. This can be done by using the FILE_GENERIC_WRITE flag which includes FILE_APPEND_DATA

hFile=CreateFile("file.txt",FILE_GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,0,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,0);

When you write to a file the file pointer moves also moves and points to the current position. If you want to write to end of file you can seek using

SetFilePointer( hFile, 0, NULL, FILE_END);

and use WriteFile as

WriteFile(hFile,buffer,strlen(buffer),&dwWritten,NULL);