pou*_*our 55 c++ windows directory copy file
在我的应用程序中,我想将文件复制到另一个硬盘,所以这是我的代码:
#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;
}
Run Code Online (Sandbox Code Playgroud)
执行此操作后,它会在D:HDD中显示一个文件testEmploi NAm.docx
但我希望他创建测试文件夹(如果它不存在).
我想在不使用Boost库的情况下这样做.
hmj*_*mjd 67
使用WINAPI CreateDirectory()函数创建文件夹.
您可以使用此功能,而无需检查目录是否已存在,因为它将失败但GetLastError()将返回ERROR_ALREADY_EXISTS:
if (CreateDirectory(OutputFolder.c_str(), NULL) ||
ERROR_ALREADY_EXISTS == GetLastError())
{
// CopyFile(...)
}
else
{
// Failed to create directory.
}
Run Code Online (Sandbox Code Playgroud)
构造目标文件的代码不正确:
string(OutputFolder+CopiedFile).c_str()
Run Code Online (Sandbox Code Playgroud)
这会产生"D:\testEmploi Nam.docx":目录和文件名之间缺少路径分隔符.示例修复:
string(OutputFolder+"\\"+CopiedFile).c_str()
Run Code Online (Sandbox Code Playgroud)
小智 35
可能最简单,最有效的方法是使用boost和boost :: filesystem函数.这样,您可以简单地构建目录并确保它与平台无关.
const char* path = _filePath.c_str();
boost::filesystem::path dir(path);
if(boost::filesystem::create_directory(dir))
{
std::cerr<< "Directory Created: "<<_filePath<<std::endl;
}
Run Code Online (Sandbox Code Playgroud)
boost :: filesystem :: create_directory - 文档
Ver*_*ahn 22
#include <experimental/filesystem> // or #include <filesystem>
namespace fs = std::experimental::filesystem;
if (!fs::is_directory("src") || !fs::exists("src")) { // Check if src folder exists
fs::create_directory("src"); // create src folder
}
Run Code Online (Sandbox Code Playgroud)
Fiv*_*rch 18
这是创建文件夹的简单方法.......
#include <windows.h>
#include <stdio.h>
void CreateFolder(const char * path)
{
if(!CreateDirectory(path ,NULL))
{
return;
}
}
CreateFolder("C:\\folder_name\\")
Run Code Online (Sandbox Code Playgroud)
以上代码适用于我.
从 c++17 开始,您可以轻松地跨平台执行此操作:
#include <filesystem>
int main() {
bool created_new_directory = false;
bool there_was_an_exception = false;
try {
created_new_directory
= std::filesystem::create_directory("directory_name");
} catch(std::exception & e){
there_was_an_exception = true;
// creation failed
}
if ((not created_new_directory) and (not there_was_an_exception)) {
// no failure, but the directory was already present.
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,如果您需要知道该目录是否实际上是新创建的,则此版本非常有用。我发现 cppreference 的文档在这一点上有点难以理解:如果目录已经存在,则此函数返回 false。
这意味着,您可以使用此方法或多或少地自动创建一个新目录。
_mkdir 也会做这个工作.
_mkdir("D:\\test");
Run Code Online (Sandbox Code Playgroud)
https://msdn.microsoft.com/en-us/library/2fkk4dzw.aspx
OpenCV 特定
Opencv 支持文件系统,可能是通过其依赖项 Boost 实现的。
#include <opencv2/core/utils/filesystem.hpp>
cv::utils::fs::createDirectory(outputDir);
Run Code Online (Sandbox Code Playgroud)