Check file before using CopyFile()

Hey guys it's me again ;-)

Today I've got a little prob with CopyFile()

 
CopyFile(TEXT("../Datalogger/Install/Install/vcredist_x64.exe"),TEXT("C:/DataLogger/vcredist_x64.exe"), false);


This code works fine for me as it copies the file correctly.
Now I was thinking about something to check if the file excists.

Is there a way like
1
2
3
4
5
6
7
8
if(CopyFile(TEXT("../Datalogger/Install/Install/vcredist_x64.exe"),TEXT("C:/DataLogger/vcredist_x64.exe"), true))
{
printf ("ERROR");
}
else
{
printf("done");
}

?

At the moment it just doesn't copy at all when I use the if-loop.
Or do I have to go the way via fopen() first to check?

Cheers.
Last edited on
`if' is not a loop

https://msdn.microsoft.com/en-us/library/windows/desktop/aa363851(v=vs.85).aspx
If (...) the new file specified by lpNewFileName already exists, the function fails.
your condition is backwards.


> At the moment it just doesn't copy at all
¿the destination file doesn't exist?
Last edited on
I would check to see if the file exist using normal method, if yes, then call copyfile.
Ok so I'm doing it like this now and it works fine.
1
2
3
4
5
6
7
8
9
10
11
if (FILE * file = fopen("../Datalogger/Install/Install/vcredist_x64.exe", "r"))
{
fclose(file);
CopyFile(TEXT("../Datalogger/Install/Install/vcredist_x64.exe"),TEXT("C:/DataLogger/vcredist_x64.exe"), true)
printf("done");

}
else
{
printf ("ERROR");
}


But I'm still wondering. MSDN tells me "If lpExistingFileName does not exist, CopyFile fails".
The programme continues anyway. So what's the purpose of this fail if I can't use it?
What do you mean "can't use it"? What is preventing you from checking the return value?
If the file does not exist, of course it fails.
There is a return error code, your not using it.
The program continues because you haven't told it to do something else.

IMO the best way is to see if the file exist before you try and copy like you did.
Last edited on
Ah ok...so I guess I have to use GetLastError() in this case?!

But I also think that checking the file before try to copy it is the best solution.
Last edited on
It is not. The `CopyFile()' function already does that.

"fails" means do nothing and return false (telling the user that it did nothing)
Last edited on
If that's what the CopyFile() function does, then I would agree.

Maybe ne555 can show us how to display an error msg if the file does not exist.
Topic archived. No new replies allowed.