C++ 无法让复制文件工作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4720876/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
can't get copyfile to work
提问by bob
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] ) "
我只是想使用 copyfile 来复制文件,就这么简单,但它不起作用。我用谷歌搜索并查看了 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. 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).
问题是我无法让它为我复制 txt 文件,我尝试以管理员身份运行它,但仍然无法正常工作。我还需要将源和目标作为 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,编译为调试,抱歉,如果我错过了什么。
回答by paxdiablo
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 firstthing 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:\somefolder
和是否c:\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. There are numerous ways you can do this, such as with CreateDirectory
, CreateDirectoryEx
or SHCreateDirectoryEx
).
要记住的一件特别的事情:CopyFile
不会为目标文件创建目录,它必须在您尝试复制之前存在。有多种方法可以执行此操作,例如使用CreateDirectory
,CreateDirectoryEx
或SHCreateDirectoryEx
)。
回答by ANTARES
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)