c语言 (vc6.0)求程序如何删除文件夹下的所有文件且不删除文件夹下的文件夹

2025-03-20 05:47:25
推荐回答(1个)
回答1:

// Win32.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "Win32.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

using namespace std;
/////////////////////////////////////////////////////////////////////////////
// The one and only application object

CWinApp theApp;

/////////////////////////////////////////////////////
// char dir[] = "d:\\test\\";
// DeleteAnyFiles(dir);
/////////////////////////////////////////////////////
void DeleteAnyFiles(const char *dir)
{

WIN32_FIND_DATA finder;
HANDLE hFileFind;
char search[MAX_PATH];
strcpy(search, dir);
strcat(search, "*.*");

hFileFind = FindFirstFile(search, &finder);

if (hFileFind != INVALID_HANDLE_VALUE)
{
do
{
char path[MAX_PATH];
strcpy(path, dir);
strcat(path, finder.cFileName);

if (!(finder.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
DeleteFile(path);

} while (FindNextFile(hFileFind, &finder) != 0);

FindClose(hFileFind);
}
}

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
int nRetCode = 0;

// initialize MFC and print and error on failure
if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
{
// TODO: change error code to suit your needs
cerr << _T("Fatal Error: MFC initialization failed") << endl;
nRetCode = 1;
}
else
{
// TODO: code your application's behavior here.
CString strHello;
strHello.LoadString(IDS_HELLO);
cout << (LPCTSTR)strHello << endl;
}

/* 测试目录为d:\\test\\,可以随意改变,但目录分割符必须是\\ */
char dir[] = "d:\\test\\";
DeleteAnyFiles(dir);
return nRetCode;
}