2009/11/01

Trying to build cross platform software isn't always easy

Trying to build cross platform software isn't always easy. For instance, the truncate function that exists on Linux and part of the unistd.h header does not exist under Windows unless you use cygwin. Windows does have the SetFilePointer to set the position and SetEndOfFile functions. You can now build a truncate function and wrap it in a #ifdef WIN32 ... #endif and it will only be used under windows.

Here is currently what I am using. Needs a bit more error checking but you can get the gist of it:


#ifdef WIN32 // Not defined in windows, translated to use SetEndOfFile function
int truncate( const char *path, const long long &length ) {
HANDLE hFile = CreateFileA( path, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
LARGE_INTEGER li;
li.QuadPart = length;
int ret = -1;
if( SetFilePointer( hFile, li.LowPart, &li.HighPart, FILE_BEGIN ) != INVALID_SET_FILE_POINTER ) {
SetEndOfFile( hFile );
ret = 0;
}
CloseHandle( hFile );
return ret;
}
#endif

No comments:

Post a Comment