-
Overwrite data in a file
Hello,
I'm trying to overwrite a number of bytes in a file. Using the standard C libraries it would be a simple case of:-
Code:
FILE *fp;
unsigned char szData[] = "Hello";
fp = fopen("file", "w");
fseek(fp, 69, SEEK_SET);
fwrite(szData, strlen(szData), 1, fp);
fclose(fp);
But using the Win32 API does not seem to be as simple. Nice one M$. :(
The best I can come up with is:-
Code:
HANDLE hFile;
unsigned char szData[]= "Hello";
DWORD dwNumBytesWritten;
hFile = CreateFile("file", GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
SetFilePointer(hFile, 69, NULL, FILE_BEGIN);
WriteFile(hFile, szData, lstrlen(szData), &dwNumBytesWritten, NULL);
CloseHandle(hFile);
Sure, it writes the data, but appends it as opposed to overwriting it, increasing the size of the file. Is there a flag or sommat I'm missing?
-
One solution is file-mapping. Map the file, change the bytes, and write the file back to disk.
Kuphryn
-
There's nothing wrong with using the C libraries or the C++ libraries for file I/O Just do like you posted with the FILE pointer or use the fstream. I'm not sure how I'd do it using only the Win32 API
-
Nice one kuphryn, I've got the file mapped now, but an M$ programmer left an int 3 (User breakpoint) in NTDLL, which is preventing me from using lstrcmpi with the mapped file. Apparently it's because RtlValidateHeap has an invalid address specified. I hate it when they do that :p
Can I use string comparison functions with mapped file memory, or should I copy any strings I wanna look at out first?
-
Yes, you can use string comparison tools on mapped files. Cast the bytes into char or TCHAR and apply the string tools. If that still does not work, consider mem tools such as memcmp.
Kuphryn
-
Whoops, my mistake. Was freeing a declared character array. :o