Reputation: 2646
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. 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?
Upvotes: 0
Views: 1240
Reputation: 5772
First of all, converting WCHARs
to char
is not a good idea, since the paths can contain Unicode characters and you'll get errors.
The second thing is that for FindFirstFile
to work, you need to add wildcards, e.g. 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
Upvotes: 2
Reputation: 409146
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
.
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.
Upvotes: 2