问题描述
在我的应用程序中,我想将文件复制到其他硬盘,这是我的代码:
In my app I want to copy a file to the other hard disk so this is my code:
#include <windows.h>
using namespace std;
int main(int argc, char* argv[] )
{
string Input = "C:\\Emploi NAm.docx";
string CopiedFile = "Emploi NAm.docx";
string OutputFolder = "D:\\test";
CopyFile(Input.c_str(), string(OutputFolder+CopiedFile).c_str(), TRUE);
return 0;
}
所以执行后,它显示在 D :
HDD文件testEmploi NAm.docx
但是我想让他创建测试文件夹(如果它不存在)。
so after executing this it shows me in the D:
HDD a file "testEmploi NAm.docx"but I want him to create the test folder if it doesn't exist.
我想要这样做而不使用Boost库。
I want to do that without using the Boost library.
推荐答案
使用WINAPI 函数
Use the WINAPI CreateDirectory()
function to create a folder.
您可以使用此函数而不检查目录是否已存在,因为它将失败,但 GetLastError()
将返回 ERROR_ALREADY_EXISTS
:
You can use this function without checking if the directory already exists as it will fail but GetLastError()
will return ERROR_ALREADY_EXISTS
:
if (CreateDirectory(OutputFolder.c_str(), NULL) ||
ERROR_ALREADY_EXISTS == GetLastError())
{
// CopyFile(...)
}
else
{
// Failed to create directory.
}
构建目标文件的代码不正确:
The code for constructing the target file is incorrect:
string(OutputFolder+CopiedFile).c_str()
这会产生D:\testEmploi Nam.docx
:目录和文件名之间缺少路径分隔符。示例修复:
this would produce "D:\testEmploi Nam.docx"
: there is a missing path separator between the directory and the filename. Example fix:
string(OutputFolder+"\\"+CopiedFile).c_str()
这篇关于如果目录不存在,则创建目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!