简体   繁体   English

如何在C ++中从给定目录中删除所有文本文件

[英]How to delete all text files from given directory in c++

I'm trying to figure out how to delete all text files from a given directory. 我试图弄清楚如何从给定目录中删除所有文本文件。 I'm using Visual c++ 2010 express, using winapi. 我正在使用Winapi使用Visual c ++ 2010 express。 I'm aware of how to delete a file if you know the exact name of that file, but I would like to delete all text files within that directory. 如果您知道文件的确切名称,我知道如何删除该文件,但是我想删除该目录中的所有文本文件。 This is my latest attempt: 这是我最近的尝试:

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 );
}

The message box only displays the folder that was selected, not the filename. 该消息框仅显示选定的文件夹,而不显示文件名。 Why is that happening? 为什么会这样呢?

A subtle problem is that you have two variables with the same name and different scope: One defined outside the loop and which is uninitialized; 一个细微的问题是,您有两个具有相同名称和不同作用域的变量:一个在循环外部定义,并且未初始化; The other declared inside the loop. 另一个在循环内声明。

The variables I'm referring to are the ones named i . 我要引用的变量是名为i的变量。

Because the one defined outside the loop is uninitialized, when you use it as an index to terminate the path its value is indeterminate and you have undefined behavior. 因为在循环外部定义的一个未初始化,所以当将其用作终止路径的索引时,其值是不确定的,并且具有未定义的行为。

First of all, converting WCHARs to char is not a good idea, since the paths can contain Unicode characters and you'll get errors. 首先,将WCHARs转换为char不是一个好主意,因为路径可能包含Unicode字符,并且会出现错误。

The second thing is that for FindFirstFile to work, you need to add wildcards, eg C:\\Path\\* . 第二件事是,要使FindFirstFile工作,您需要添加通配符,例如C:\\Path\\*

Here's an example on MSDN which enumerates files in a directory: http://msdn.microsoft.com/en-us/library/windows/desktop/aa365200%28v=vs.85%29.aspx 这是在MSDN上枚举目录中文件的示例: http : //msdn.microsoft.com/zh-cn/library/windows/desktop/aa365200%28v=vs.85%29.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM