Question

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);
Was it helpful?

Solution 2

The call to SetFilePointer() is unrequired as the subsequent WriteFile() call will write data after the data written by the first WriteFile(): remove the call to SetFilePointer().

The call to SetFilePointer() is moving the file pointer dwWritten bytes beyond its current location, and the current location is at the end of the data just written.

Check result of WriteFile() to ensure data was successfully written and it is important to include the value of GetLastError(), or its description using FormatMessage(), in any error messages so the actual cause of the failure is known:

if(hFile==INVALID_HANDLE_VALUE)
{
    char error_msg[128];
    sprintf(error_msg, "Could not create/open a file: %d", GetLastError());
    MessageBox(0,error_msg,"Error",16);
    return 0;
}

OTHER TIPS

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); 

If you want to create text lines, you also need to output CR+LF characters at the end of each line e.g.:

char[] crlf = "\r\n";

and add

WriteFile(hFile, crlf, sizeof(crlf), &dwWritten, 0);

after writing each string.

Alternatively, use file streams instead of handles, the following code is equivalent to your code:

char buffer[]="Write this text to file";
FILE *stream;
if ((stream = fopen("file.txt", "w+")) == NULL)
{    MessageBox(0,"Could not create/open a file","Error",16);
    return 0;
}
fprintf(stream, "%s\n", buffer);
fseek(stream, 0L, SEEK_END);
fprintf(stream, "%s\n", buffer);
fclose(stream);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top