views:

159

answers:

3

I'm attempting to shrink a file in place.
I'm replacing the contents of one file with those of another and when I'm done I want to make sure if the source file is smaller than the dest file, the dest file shrinks correctly.

(Why: because the dest file is a backup and writing to the media is very expensive, so I only write the deltas to the backup)

1.) HANDLE hDest =(HANDLE)_get_osfhandle( fileno(backupFile.GetBufferedHandle()) );
2.) DWORD startingSize = GetFileSize(hDest, NULL);
3.) DWORD dwPtr = SetFilePointer(hDest, newSize, NULL, FILE_BEGIN);
4.) int err = GetLastError();
5.) if (dwPtr != INVALID_SET_FILE_POINTER)
6.) {   err = SetEndOfFile(hDest); 
7.)     if(err == 0) 
8.)      err = GetLastError();
9.)     err = SetFileValidData(hDest, newSize);
10.) }
11.) DWORD endingSize = GetFileSize(hDest, NULL);

I'm getting an error on line 8 that is 1224... I'm wondering if anyone can tell me why, or suggest a better approach.

+3  A: 

"net helpmsg 1224" -> The requested operation cannot be performed on a file with a user-mapped section open.

And from MSDN for SetEndOfFile:

If CreateFileMapping is called to create a file mapping object for hFile, UnmapViewOfFile must be called first to unmap all views and call CloseHandle to close the file mapping object before you can call SetEndOfFile.

MSN
Beat me by two mins :P
Billy ONeal
Thank you.. Turns out the class that I was using to open the file (a new wheel) was doing some mapping. When I brought the code down to the base fopen... it worked correctly.
baash05
Thanks for the "net helpmsg", now I can finally get rid of ERRLOOK.EXE :)
Jonas Gulle
A: 

You got an error code of 0 which means success (ERROR_SUCCESS) and it did work, see line 6 in the sample you provided. Now why did you call a GetLastError immediately after the check in line 7? By the way, I think you should be using ERROR_SUCCESS instead of 0. The reference to the error codes can be found here. Or did you actually mean it occurred in line 9?

Can you confirm this? Hope this helps, Best regards, Tom.

tommieb75
`SetEndOfFile` returns zero on failure. See http://msdn.microsoft.com/en-us/library/aa365531%28VS.85%29.aspx.
Billy ONeal
@BillyONeal...Whoopsie! My bad!...tis late for me, need sleep...I apologize for my misunderstanding... :( Sorry
tommieb75
A: 

That error translates to The requested operation cannot be performed on a file with a user-mapped section open.

Do you have any memory mapped segments of that file?

Billy ONeal
I don't think so.. I'm using a custom file library (yeah newly invented wheel). I guess I'll have to dig.
baash05