MoveFile() Works, but returns error 2 (file not found)

2.2k views Asked by At

I'm using the function Movefile() (in C). I can see the file moved from the source folder to the destination (means the MoveFile success) but when I do GetLastError() I get error no. 2 (ERROR_FILE_NOT_FOUND).

What can be the problem?

The code is:

_snprintf(szSrcPath, MAX_PATH, "%s/%s/%s.jpg", NPath, imagePathFromAdmin, username);
_snprintf(szDestPath, MAX_PATH, "%s/Images/Storage/%s/%d/%s.jpg", NPath, domain, sub_folder, username);
strcpy(imagePathStorgae,szDestPath);
MoveFile(szSrcPath,szDestPath);
err=GetLastError();
2

There are 2 answers

0
Some programmer dude On BEST ANSWER

Do not get the error code if a function succeeds, the value is not valid. Instead check the value returned by the actual function (i.e. the MoveFile function return value) and if that indicates that an error happened, then you can check what the error was.

0
David Heffernan On

You are only meant to call GetLastError if the API function call reported failure. Check the return value of both CopyFile and MoveFile. If either returns FALSE then the API call failed and then, and only then, is it valid to call GetLastError.

The documentation states it like this:

Return value

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

What is happening is that MoveFile succeeds and does not modify the last error value. Then when you call GetLastError it returns an error code for some other call to an API function, that happened before you called MoveFile. You should write the code like this:

if (!MoveFile(szSrcPath,szDestPath))
{
    DWORD err = GetLastError();
    // handle the error
}