【问题标题】:How to delete all text files from given directory in c++如何从c ++中的给定目录中删除所有文本文件
【发布时间】:2014-02-17 07:37:44
【问题描述】:

我试图弄清楚如何从给定目录中删除所有文本文件。我正在使用 Visual c++ 2010 express,使用 winapi。如果您知道该文件的确切名称,我知道如何删除该文件,但我想删除该目录中的所有文本文件。这是我最近的尝试:

void deleteFiles( WCHAR file[] )
{
  // WCHAR file[] is actually the directory path. i.e C:\Users\TheUser\Desktop\Folder\

  // Convert from WCHAR to char for future functions
  char filePath[ MAX_PATH ];
  int i;
  for( int i = 0; file[ i ] != '\0'; i++ )
  {
    // Cycle through each character from the array and place it in the new array
    filePath[ i ] = file[ i ];
  }
  // Place the null character at the end
  filePath[ i ] = '\0';

  // Generate WIN32_FIND_DATA struct and FindFirstFile()
  WIN32_FIND_DATA fileData;
  FindFirstFile( file, &fileData );

  // Display the filename
  MessageBox( NULL, fileData.cFileName, L"Check", MB_OK );
}

消息框只显示被选中的文件夹,而不是文件名。为什么会这样?

【问题讨论】:

  • 如果不使用,为什么要声明“filePath”?
  • 这是我之前尝试过的不同解决方案。我想我忘了把它拿出来。

标签: c++ file winapi delete-file


【解决方案1】:

一个微妙的问题是您有 两个 具有相同名称和不同范围的变量:一个在循环之外定义并且未初始化;另一个在循环内声明。

我所指的变量是名为 i 的变量。

因为在循环外定义的那个是未初始化的,当你用它作为索引来终止路径时,它的值是不确定的并且你有未定义的行为。

【讨论】:

    【解决方案2】:

    首先,将WCHARs 转换为char 不是一个好主意,因为路径可能包含Unicode 字符并且会出现错误。

    第二件事是FindFirstFile 工作,你需要添加通配符,例如C:\Path\*.

    这是 MSDN 上的一个示例,它枚举目录中的文件:http://msdn.microsoft.com/en-us/library/windows/desktop/aa365200%28v=vs.85%29.aspx

    【讨论】:

      猜你喜欢
      • 2022-08-09
      • 2023-03-04
      • 2012-04-14
      • 2016-08-24
      • 2015-01-20
      • 1970-01-01
      • 2012-03-05
      • 2015-10-08
      • 1970-01-01
      相关资源
      最近更新 更多