我正在尝试弄清楚如何从给定目录中删除所有文本文件。我正在使用 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 );
}
消息框只显示选中的文件夹,不显示文件名。为什么会这样?
最佳答案
一个微妙的问题是您有两个 具有相同名称和不同范围的变量:一个在循环外定义并且未初始化;另一个在循环内声明。
我指的变量是名为i
的变量。
因为在循环外定义的那个是未初始化的,当你用它作为索引来终止路径时,它的值是不确定的,你有未定义的行为。
关于c++ - 如何从C++中的给定目录中删除所有文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21823274/