Velvet Star Monitor

Standout celebrity highlights with iconic style.

general

can't get copyfile to work

Writer Sebastian Wright

i am just trying to use copyfile to copy a file, it is as simple as that but it wont work. i have googled it and looked at 20 links and they all say "object.CopyFile ( source, destination[, overwrite] ) "

The problem is i can't get it to copy the txt file for me, i have tryed running it as an admin but still does not work. also i need to put the source and destination as lpctstr (because it wont compile with out using Multi-Byte Character and my other code will not work unless i Use Unicode Character Set).

My code is

#include <iostream>
#include <Windows.h>
using namespace std;
int main()
{ CopyFile("C:\\Somefolder\\file.txt","C:\\folder\\file.txt",0); return 0;
}

i am running windows 7, vc++ 2010, compiling as debug, sorry if i missed anything.

3

2 Answers

Replace the line:

CopyFile("C:\\Somefolder\\file.txt","C:\\folder\\file.txt",0);

with:

BOOL b = CopyFile("C:\\Somefolder\\file.txt","C:\\folder\\file.txt",0);
if (!b) { cout << "Error: " << GetLastError() << endl;
} else { cout << "Okay " << endl;
}

That should tell you if and why it's failing. The error code, once you have it, can be looked up here.


And if, as your comment indicates, you're getting ERROR_PATH_NOT_FOUND, the first thing I'd be looking at is whether the paths c:\somefolder and c:\folder exist as well as the actual source file c:\somefolder\file.txt.

One special thing to keep in mind: CopyFile won't create the directory for the target file, it has to exist before you try to copy. There are numerous ways you can do this, such as with CreateDirectory, CreateDirectoryEx or SHCreateDirectoryEx).

7

you have to check to close the file with fclose(FILE*) if you used fopen(...) or CloseHandle(HANDLE) if you used a HANDLE for the file (like hFile...)... for me in C it works!

ANTARES (IT)

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.