Check file before using CopyFile()

Sep 9, 2015 at 4:41pm
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 Sep 9, 2015 at 4:44pm
Sep 9, 2015 at 5:07pm
`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 Sep 9, 2015 at 5:11pm
Sep 9, 2015 at 5:13pm
I would check to see if the file exist using normal method, if yes, then call copyfile.
Sep 9, 2015 at 5:48pm
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?
Sep 9, 2015 at 5:50pm
What do you mean "can't use it"? What is preventing you from checking the return value?
Sep 9, 2015 at 5:58pm
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 Sep 9, 2015 at 6:00pm
Sep 9, 2015 at 6:16pm
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 Sep 9, 2015 at 6:17pm
Sep 9, 2015 at 6:47pm
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 Sep 9, 2015 at 6:48pm
Sep 11, 2015 at 3:41am
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.