preallocating logging files for performance purposes
-
I'm looking for some VS c++ code that 1) preallocates a file 2) opens a preallocated file for sequential writing starting at the beginning of the file 3) writes(appends) ascii message strings to the file. Thanks
-
I'm looking for some VS c++ code that 1) preallocates a file 2) opens a preallocated file for sequential writing starting at the beginning of the file 3) writes(appends) ascii message strings to the file. Thanks
I'm not sure exactly what you mena by point 1, but opening a file for appending is quite straightforward, and writing text is even more so. Take a look at the STL file stream classes[^] or use the Createfile[^] and associated functions.
I must get a clever new signature for 2011.
-
I'm looking for some VS c++ code that 1) preallocates a file 2) opens a preallocated file for sequential writing starting at the beginning of the file 3) writes(appends) ascii message strings to the file. Thanks
You need to seek to what you want to be the end of the pre-allocated space, then set the EOF marker, then seek back to the start so you are writing from the beginning of the file, like so
HANDLE hFile = CreateFile("C:\\test", GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile != INVALID_HANDLE_VALUE) {
SetFilePointer(hFile, 4 * 1024 * 1024, NULL, SEEK_SET); //seek to 4MB (pre-allocate 4MB)
SetEndOfFile(hFile); //set the EOF to pre-allocate the space
SetFilePointer(hFile, 0, NULL, SEEK_SET); //seek back to the start for writing
//write to the file with WriteFile()
CloseHandle(hFile);
}Edit: I missed part 3... quite simply seek to the end of the data in the file to append to it.
SetFilePointer(hFile, 0, NULL, SEEK_END); //If you want to append to the end of the entire file (including after the pre-allocated space)
SetFilePointer(hFile, nDataLength, NULL, SEEK_SET); //if you are keeping track of the length of the data you have written to the file with the variable nDataLengthWriting to a file is pretty straight forward. You just need a buffer and the length of data you are writing
LPSTR szWrite = "hello world";
DWORD nLength = strlen(szWrite);
DWORD nBytesWritten;
WriteFile(hFile, szWrite, nLength, &nBytesWritten, NULL);
CloseHandle(hFile);If you are writing strings in unicode you need to multiply the length by
sizeof(wchar_t)
orsizeof(TCHAR)
Finally, All file writes (and reads) are sequential for all APIs that I know of. It moves the file pointer to the end of the data you have just written (or read)modified on Wednesday, January 12, 2011 11:23 AM
-
I'm looking for some VS c++ code that 1) preallocates a file 2) opens a preallocated file for sequential writing starting at the beginning of the file 3) writes(appends) ascii message strings to the file. Thanks