【问题标题】:creating multiple folders inside current directory in c++在 C++ 中的当前目录中创建多个文件夹
【发布时间】:2017-02-27 07:58:33
【问题描述】:

我想在 C++ 的当前目录中使用循环创建一些文件夹。我已经编写了代码,但出现以下错误。

无法将参数 '1' 的 'std::string {aka std::basic_string}' 转换为 'const char*' 到 'void CreateFolder(const char*)'

我的代码是:

 #include<iostream>
 #include<cstdio>
 #include<cstring>
 #include <windows.h>
 #include <cstdio>
 #include<cstdlib>
 #include<fstream>
 #include <sstream>
 using namespace std;

#define total 28

std::string to_string(int i) {
   std::stringstream s;
   s << i;
   return s.str();
}


void CreateFolder(const char * path)
{
    if(!CreateDirectory(path ,NULL))
    {
        return;
    }
}


main()
{
    string folder_name;
    string suffix = ".\\"; // for current directory

     for(int i=0;i<=total;i++)
    {
        folder_name=suffix+to_string(i);
        CreateFolder(folder_name);

    }

} 

我将如何创建名为 0,1... 到 28 的文件夹?

【问题讨论】:

  • 作为提示:反斜杠在字符串或字符文字中是什么意思?想一想。
  • CreateFolder(folder_name); 替换为CreateFolder(folder_name.c_str); 并查找string::c_str 方法。
  • 顺便说一句,这个问题的标题完全具有误导性。这应该被标记为 C++。这更像是一个 C++ 问题,而不是一个 WINAPI 问题。
  • 错误信息不是很清楚吗?您的下一个任务是学习如何理解错误消息。
  • 题外话:使用当前目录是错误的。没有安全的方法来使用它,因为您不能施加任何限制或推断出任何保证。在任何时候,它都会指向 some 目录,并且您无法控制它是哪个目录,或者它何时更改。使用绝对路径。

标签: c++ winapi directory


【解决方案1】:

您不能直接将std::string 传递为char*。通过使用c_str() 函数,您可以从std::string 检索原始char*

//std::string -> const char*
CreateFolder(folder_name.c_str());

【讨论】:

  • 编译时出现以下错误:错误:无法将参数 '1' 的 'LPCWSTR {aka const wchar_t*}' 转换为 'LPCSTR {aka const char*}' 到 'BOOL CreateDirectoryA(LPCSTR, LPSECURITY_ATTRIBUTES)' @Doncot
  • 哦,对不起。看起来您正在使用多字符设置(= 非 UNICODE)。修正我的答案。
  • @Doncot: "you're using Multi-char settings" - 它被称为 Multi-Byte (在 MBCS 中),实际上是Windows 中的 DBCS。这是您不想想要使用的一种设置。真正的解决方法是使用std::wstring 并调用CreateDirectoryW
猜你喜欢
  • 2012-12-17
  • 2019-06-22
  • 2021-12-05
  • 2020-11-18
  • 1970-01-01
  • 2022-01-15
  • 2013-08-06
  • 2011-07-05
相关资源
最近更新 更多