HANDLE hFile = CreateFile("test.txt", FILE_GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
ULONG nWritten = 0;
WriteFile(hFile, "line-to-be-appened\r\n", strlen("line-to-be-appened\r\n"), &nWritten, NULL);
CloseFile(hFile);
When the above code snippet opens an existing file test.txt
and is expected to append "line-to-be-appened\r\n"
to the end of the file. However, it just overwrites the file.
How can I make it append at the end?
When you are opening the file, its read/write pointer is at the beginning of the file by default. Thus, you are writing at the front of the file, overwriting whatever is already there.
To append at the end of the file, you need to seek to the end of the file before writing, either by:
SetFilePointer/Ex()
, eg:HANDLE hFile = CreateFile("test.txt", FILE_GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
SetFilePointer(hFile, 0, NULL, FILE_END); // <-- add this
ULONG nWritten = 0;
WriteFile(hFile, "line-to-be-appened\r\n", strlen("line-to-be-appened\r\n"), &nWritten, NULL);
CloseFile(hFile);
FILE_APPEND_DATA
flag by itself, which will then handle the seeking for you, eg:HANDLE hFile = CreateFile("test.txt", FILE_APPEND_DATA, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
ULONG nWritten = 0;
WriteFile(hFile, "line-to-be-appened\r\n", strlen("line-to-be-appened\r\n"), &nWritten, NULL);
CloseFile(hFile);
FILE_GENERIC_WRITE
includes both FILE_WRITE_DATA
and FILE_APPEND_DATA
, but FILE_WRITE_DATA
prevents FILE_APPEND_DATA
from seeking automatically:
For local files, write operations will not overwrite existing data if [FILE_APPEND_DATA] is specified without FILE_WRITE_DATA.