简体   繁体   English

无法让复制文件工作

[英]can't get copyfile to work

i am just trying to use copyfile to copy a file, it is as simple as that but it wont work.我只是想使用 copyfile 来复制文件,就这么简单,但它不起作用。 i have googled it and looked at 20 links and they all say " object.CopyFile ( source, destination[, overwrite] ) "我用谷歌搜索并查看了 20 个链接,他们都说“ 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.问题是我无法让它为我复制 txt 文件,我尝试以管理员身份运行它,但仍然无法正常工作。 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).我还需要将源和目标作为 lpctstr (因为它不会在不使用多字节字符的情况下编译,除非我使用 Unicode 字符集,否则我的其他代码将无法工作)。

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.我正在运行 Windows 7,vc++ 2010,编译为调试,抱歉,如果我错过了什么。

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 .如果,如您的评论所示,您收到ERROR_PATH_NOT_FOUND ,我首先要看的是路径c:\\somefolderc:\\folder存在以及实际的源文件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.要记住的一件特别的事情: CopyFile不会为目标文件创建目录,它必须在您尝试复制之前存在。 There are numerous ways you can do this, such as with CreateDirectory , CreateDirectoryEx or SHCreateDirectoryEx ).有很多方法可以做到这一点,例如使用CreateDirectoryCreateDirectoryExSHCreateDirectoryEx )。

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!如果您使用 fopen(...) 或 CloseHandle(HANDLE) 如果您使用文件的句柄(如 hFile...)...它有效!

ANTARES (IT) ANTARES (IT)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM