Windows API 实现查找、删除任意类型的文件_VERSION20120612(vc6.0调试通过)(2012.6.12最新修改)

// FileToolsV20120605.cpp : Defines the entry point for the application.
//
//用vc6.0建立一个win32简单应用程序

#include "stdafx.h"
#include <stdio.h>
#include <fcntl.h>
#include <io.h>
#include <iostream>
#include <fstream>
#include <conio.h>
#include <SHELLAPI.H>

//////////////////////////////////////////

//调试开关:

//#define FLAG_DEBUG



//////////////////////////////////////////

//要删除的目录

#define FIND_FILE_PATH "C:\\Program Files"

//要删除的文件类型

#define FIND_FILE_TYPE ".exe"

//////////////////////////////////////////



#define FILE_NAME_TYPE "*.*"







//最大的文件查找字节数

#define MAX_FIND_PATH 1000



//函数返回值:

#define RTN_OK (0)

#define RTN_ERR (1)



//休眠秒数

#define SLEEP_SECOND 100



//LOGO字符串

#define STR_LOGO "\---------------------------------------------------------------┐\n\
│Files Toos [版本 FTV01R01C01]                                  │ \n\
│ Build By BinG @2012.3, Email:[email protected].               │ \n\
│ 版权所有 (c) 2012 Zkf39219。保留所有权利。                    │ \n\
└---------------------------------------------------------------┘\n"
    
    
    
    //帮助信息字符串
    
#define STR_HELP ""\
    " 查看帮助\n"\
    "m 修改配置信息\n"\
    "q 退出\n"\
    "d 打开调试开关\n"\
    "c 清屏\n"\
    "t 测试\n"\
    "-----------------------------------\n"\
    "自己输入:y,自己不想输入:<任意键>\n"

//往屏幕打印信息    
#define PRINTTOSCR(str) do\
{\
printf("%s",str);\
} while (0);





enum
{
    FLAG_ZERO, //0 :默认0
    FLAG_VIEW_FILE,//1 :查看文件 
    FLAG_DELETE, //2 :删除文件 
    FLAG_INIT_OK, //3 :全局变量初始化标志
    FLAG_INIT_NO, //4 :全局变量没有初始化
    FLAG_ONE_LOG, //5 :打开程序只能有一个log标志
    FLAG_FILENAME_TIME, //6 :文件以时间命令。
    FLAG_FILENAME_ZHID, //7 :文件指定命名
};







//-----------------------------------------------------------

// 函数声明

//-----------------------------------------------------------

#ifdef __cplusplus
extern "C" {    
#endif //__cplusplus

    void InitGlobalVar();
    void PrintLocalTime(void* flag);
    void fOpenFileFp(FILE** fp);
    void fCloseFileFp(FILE** fp);
    void VisitAllFiles(char * lpPath);
    void GetCurSysTime(char* str);
    void FileOptions();
    void CloseOrFreeGlobalVar();
    void DebugAndPrintAllGlobalVar();
    int FileOpt();
    void ExecAppByCmd();

#ifdef __cplusplus    
}
#endif //__cplusplus





#ifndef _USE_OLD_IOSTREAMS

using namespace std;

#endif



// maximum mumber of lines the output console should have

static const WORD MAX_CONSOLE_LINES = 500;

//-----------------------------------------------------------

// 全局变量声明(定义) 

//-----------------------------------------------------------

//全局的文件计数与文件清理计数

static long g_lCheckFileNumber;

static long g_lCheckOkFileNumber;

static long g_lClearFileNumber;

static int g_flagDeleteFile;

static int g_flagOnlyOneLog = FLAG_ONE_LOG;



//////////////////////////////////////////////

//用于全局初始化函数中的是否初始化标志。

//初始化时置1

//调用CloseOrFreeGlobalVar函数时重新置0

//默认值:FLAG_INIT_NO 0

static int g_flagInitFuncIsFinish=FLAG_INIT_NO;

/////////////////////////////////////////////

///全局的指针变量



/* 定义全局的FILE类型指针,供写日志 */

FILE* g_fpLog;

FILE* g_fpCheckOK;

/////////////////////////////////////////////

//定义全局的查找文件路径及类型

char g_strFindFilePath[MAX_FIND_PATH];

char g_strFindFileType[10];



//全局的时间字符串

char g_pStrTime[50];



//全局的文件路径名字符串

char g_strTemFileName[80];



//函数访问次数

int g_iCount = 0;






void RedirectIOToConsole()
{
    
    int hConHandle;
    long lStdHandle;
    CONSOLE_SCREEN_BUFFER_INFO coninfo;
    FILE *fp;
    
    // 分配一个控制台程序
    AllocConsole();

    // 设置足够大的屏幕缓存可以让我们滑动文本
    GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &coninfo);

    // 设置控制台屏幕的高度 
    coninfo.dwSize.Y = MAX_CONSOLE_LINES;
    
    // 设置控制台屏幕缓存大小 
    SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), coninfo.dwSize);
    
    // 获取标准输出句柄
    lStdHandle = (long)GetStdHandle(STD_OUTPUT_HANDLE);
    
    //打开标准输出句柄,类似打开文件的方式如fopen,返回一个文件描述符
    hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
    
    // 以可写的方式打开 
    fp = _fdopen( hConHandle, "w" ); 
    *stdout = *fp;
    setvbuf( stdout, NULL, _IONBF, 0 );
    
    // redirect unbuffered STDIN to the console
    lStdHandle = (long)GetStdHandle(STD_INPUT_HANDLE); 
    hConHandle = _open_osfhandle(lStdHandle, _O_TEXT); 
    fp = _fdopen( hConHandle, "r" );
    *stdin = *fp; 
    setvbuf( stdin, NULL, _IONBF, 0 ); 
    
    // redirect unbuffered STDERR to the console
    lStdHandle = (long)GetStdHandle(STD_ERROR_HANDLE);
    hConHandle = _open_osfhandle(lStdHandle, _O_TEXT); 
    fp = _fdopen( hConHandle, "w" ); 
    *stderr = *fp; 
    setvbuf( stderr, NULL, _IONBF, 0 ); 
    
    // make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog
    // point to console as well
    ios::sync_with_stdio();
} 



void test()
{
    int iVar;
    RedirectIOToConsole(); 
    
    // test stdio
    fprintf(stdout, "Test output to stdout\n"); 
    fprintf(stderr, "Test output to stderr\n");
    fprintf(stdout, "Enter an integer to test stdin: "); 
    scanf("%d", &iVar); 
    printf("You entered %d\n", iVar);
    
    //test iostreams
    cout << "Test output to cout" << endl;
    cerr << "Test output to cerr" << endl;
    clog << "Test output to clog" << endl;
    cout << "Enter an integer to test cin: ";
    cin >> iVar;
    cout << "You entered " << iVar << endl;
} 





int APIENTRY WinMain(HINSTANCE hInstance,
                     
                     HINSTANCE hPrevInstance,
                     
                     LPSTR lpCmdLine,
                     
                     int nCmdShow)
                     
{
    
    // TODO: Place code here.
    
    
    
    //test();
    
    RedirectIOToConsole();
    
    (void)FileOpt();
    
    return 0;
    
}







//-----------------------------------------------------------

// main函数 

//-----------------------------------------------------------

#if 1

int FileOpt()

{
    
#if 1
    
    InitGlobalVar();
    
    FileOptions();
    
    
    
#ifdef FLAG_DEBUG
    
    DebugAndPrintAllGlobalVar();
    
#endif
    
    CloseOrFreeGlobalVar();
    
    
    
#endif
    
    return 0;
    
}

#endif // 0







//-----------------------------------------------------------

// 函数实现 

//-----------------------------------------------------------



/************************************************************************/

/*说明: 同时打印输出到文件及屏幕上 */

/* stream: 文件句柄,即文件描述符 */

/* format: 格式字符串 */

/* Build by [email protected] */

/************************************************************************/

void WriteFormatted (FILE * stream, char * format, ...)

{
    
    /*BEGIN: Modify by zkf39219 @ 2012.511 for pointer NULL error */
    
    if (NULL == stream)
        
    {
        
        printf("FILE pointer init error:IS NULL!!!\n");
        
        return;
        
    }
    
    /*END: Modify by zkf39219 @ 2012.5.11 for pointer NULL error */
    
    
    
    //获取时间信息
    
    GetCurSysTime(g_pStrTime);
    
    
    
    va_list args;
    
    va_start (args, format);
    
    vfprintf (stream, format, args);
    
    vprintf (format, args);
    
    va_end (args);
    
}




/////////////////////////////////////////////////////

//功能:

//1.打开文件句柄

//2.标志不同输出文件不同:

//3.标志flag为FLAG_FILENAME_TIME:1时:文件名用时间命名

//4.标志flag为FLAG_FILENAME_ZHID:2时:指定命名

void fOpenFileFp(FILE** fp,
                 
                 int flag)//标志,1:文件名用时间命名,2:指定命名
                 
{
    
    if (NULL == *fp)
        
    {
        
        *fp = (FILE*)malloc(sizeof(FILE));
        
        
        
        if (NULL == *fp)
            
        {
            
            printf("malloc error!!!\n");
            
            return;
            
        }
        
    }
    
    
    
    if (FLAG_ONE_LOG == g_flagOnlyOneLog)
        
    {
        
        char strTemFileName[80];
        
        GetCurSysTime(strTemFileName);
        
        strcat(strTemFileName,".log");
        
        strcpy(g_strTemFileName,strTemFileName);
        
    }
    
    
    
    
    
    if (FLAG_FILENAME_TIME == flag && (*fp = fopen(g_strTemFileName, "a")) == NULL)
        
    {
        
        WriteFormatted(g_fpLog,"Can't open %s \n", g_strTemFileName);
        
        exit(-1);
        
    }
    
    else if(FLAG_FILENAME_ZHID == flag && (*fp = fopen("OutPut.txt", "a")) == NULL)
        
    {
        
        WriteFormatted(g_fpLog,"Can't open %s \n", g_strTemFileName);
        
        exit(-1);
        
    }
    
    
    
    g_flagOnlyOneLog++;
    
}



//调试时打印所有全局变量

void DebugAndPrintAllGlobalVar()

{
    
    WriteFormatted(g_fpLog,
    "g_lCheckFileNumber :Ox%08x\n\
g_lCheckOkFileNumber :Ox%08x\n\
g_lClearFileNumber :Ox%08x\n\
g_flagDeleteFile :Ox%08x\n\
g_fpLog :Ox%08x\n\
g_fpCheckOK :Ox%08x\n\
g_pStrTime :Ox%08x\n\
g_strFindFilePath :Ox%08x\n\
g_strFindFileType :Ox%08x\n\
g_iCount :Ox%08x\n\
g_flagInitFuncIsFinish:Ox%08x\n--->%s\n",
g_lCheckFileNumber,
g_lCheckOkFileNumber,
g_lClearFileNumber,
g_flagDeleteFile,
g_fpLog,g_fpCheckOK,g_pStrTime,g_strFindFilePath,
g_strFindFileType,
g_iCount,
g_flagInitFuncIsFinish,
(g_flagInitFuncIsFinish==FLAG_INIT_NO)?"内存已释放":"危险:内存没有释放");
    
    
    
    //释放指针g_fpLog的前提是标志g_flagInitFuncIsFinish置FLAG_INIT_NO
    
    //即其它内存已经释放
    
    if (FLAG_INIT_NO == g_flagInitFuncIsFinish)
        
    {
        
        fCloseFileFp(&g_fpLog);
        
        printf("g_fpLog :Ox%08x\n",g_fpLog);
        
    }
    
}



//////////////////////////////////////////////////////

//功能:

// 初始化全局变量

// 为了避免重复初始化,该函数初始化完成后置标志为FLAG_INIT_OK

void InitGlobalVar()

{
    
    //先判断是否已经初始化,已初始化直接返回
    
    if (FLAG_INIT_OK == g_flagInitFuncIsFinish)
        
    {
        
        return;
        
    }
    
    
    
    g_lCheckFileNumber = 0;
    
    g_lCheckOkFileNumber = 0;
    
    g_lClearFileNumber = 0;
    
    g_flagDeleteFile = FLAG_VIEW_FILE;
    
    
    
    g_fpLog = NULL;
    
    g_fpCheckOK = NULL;
    
    
    
    /* 初始化全局变量 g_fpLog */
    
    if (NULL == g_fpLog)
        
    {
        
        fOpenFileFp(&g_fpLog,FLAG_FILENAME_TIME);
        
    }
    
    
    
    /* 初始化全局变量 fp */
    
    if (NULL == g_fpCheckOK)
        
    {
        
        fOpenFileFp(&g_fpCheckOK,FLAG_FILENAME_ZHID);
        
    }
    
    
    
    /* 初始化全局变量 */
    
    GetCurSysTime( g_pStrTime );
    
    
    
    //strcpy(g_strFindFilePath,FIND_FILE_PATH);
    
    //strcpy(g_strFindFileType,FIND_FILE_TYPE);
    
    
    
    g_iCount = 0;
    
    g_flagInitFuncIsFinish = FLAG_INIT_OK;
    
}

void FreePTime(PSYSTEMTIME pTime)

{
    
    /* 一定要进行下面判断,否则会造成重复释放NULL地址而崩溃 */
    
    if (NULL != pTime)
        
    {
        
        free(pTime);
        
        pTime = NULL;
        
    }
    
}







//打开文件句柄

void fCloseFileFp(FILE** fp)

{
    
    if (*fp)
        
    {
        
        fclose(*fp);
        
        *fp = NULL;
        
    }
    
}



///////////////////////////////////////

//函数功能:

//1.对全局的指针进行释放,并指向NULL

//2.对全局变量置默认值

//3.如果发现初始化标志没有OK,返回

void CloseOrFreeGlobalVar()

{
    
    if (FLAG_INIT_NO == g_flagInitFuncIsFinish )
        
    {
        
        return;
        
    }
    
    
    
    /* 调试时不在这释放日志内存指针g_fpLog,由调试函数释放 */
    
#ifndef FLAG_DEBUG
    
    fCloseFileFp(&g_fpLog);
    
#endif
    
    fCloseFileFp(&g_fpCheckOK);
    
    
    
    g_lCheckFileNumber = 0;
    
    g_lCheckOkFileNumber = 0;
    
    g_lClearFileNumber = 0;
    
    g_flagDeleteFile = FLAG_VIEW_FILE;
    
    
    
    //下面两行存在重大隐患:指针虽然指向NULL,但其内存空间没有释放,造成内存泄漏
    
    //fCloseFileFp函数里有指向NULL,所以这里不要再指向NULL.
    
    //g_fpLog = NULL;
    
    //g_fpCheckOK = NULL;
    
    
    
    g_flagInitFuncIsFinish = FLAG_INIT_NO;
    
    
    
#ifdef FLAG_DEBUG
    
    //上面没有释放的句柄应该在这里面释放
    
    DebugAndPrintAllGlobalVar();
    
#endif
    
}



////////////////////////////////////////////////////////////////////////////

/* Modify by zengwenwu @ 2012-3-19 :增加一标志,提供不同打印要求 */

//1:打印长时间

//0:短时间

//-1:不打印,相当于只对pTime做赋值

void GetCurSysTime(char* str)

{
    
    LPSYSTEMTIME pstTemSysTime = NULL;
    
    
    
    pstTemSysTime = (LPSYSTEMTIME)malloc( sizeof(SYSTEMTIME) );
    
    
    
    if ( NULL == pstTemSysTime )
        
    {
        
        WriteFormatted(g_fpLog,"SYSTEMTIME malloc is err\n" );
        
        return;
        
    }
    
    
    
    memset(pstTemSysTime,0,sizeof(LPSYSTEMTIME));
    
    
    
    GetLocalTime( pstTemSysTime );
    
    
    
    sprintf((char*)str,"%04d-%02d-%02d %02d_%02d_%02d %03d",
        
        pstTemSysTime->wYear,
        
        pstTemSysTime->wMonth,
        
        pstTemSysTime->wDay,
        
        pstTemSysTime->wHour,
        
        pstTemSysTime->wMinute,
        
        pstTemSysTime->wSecond,
        
        pstTemSysTime->wMilliseconds
        
        );
    
}


/////////////////////////////////////////////////////////////////

//Function:

// Visit all folders and files 

//

//Paremeter:

// char *lpPath -- path of file

//

//Return:

// void

//



void VisitAllFiles(char * lpPath)
{    
    Sleep(SLEEP_SECOND);    
    char szFind[MAX_PATH];     
    WIN32_FIND_DATA FindFileData;    
    char chTemPath[MAX_FIND_PATH];
    
    strcpy(chTemPath,lpPath);

    int n = strlen(chTemPath);
    if (chTemPath[n-1] == '\\' || chTemPath[n-1] == '/')
    {        
        WriteFormatted(g_fpLog,"%s\n",chTemPath);
        chTemPath[n-1] = '\0';
        WriteFormatted(g_fpLog,"%s\n",chTemPath);
    }
    
    
    strcpy(szFind,chTemPath);
    strcat(szFind,"\\*.*");
    
//     WriteFormatted(g_fpLog,"%s\n",chTemPath);
//     WriteFormatted(g_fpLog,"%d %d\n",'\\','/');
    
    /* 对全局时间g_pTime变量赋值 */    
    if (0 == g_iCount++)
    {        
        WriteFormatted(g_fpLog,"查找%s下%s类型的文件\n",g_strFindFilePath,g_strFindFileType);        
        WriteFormatted(g_fpLog,"BEGIN-------------------------------------------------%s\n",g_pStrTime);        
        WriteFormatted(g_fpCheckOK,"%s\n","\n\n////////////////////////////////////////////////////////////////");        
        WriteFormatted(g_fpCheckOK,"查找目录%s下%s类型的文件\n",g_strFindFilePath,g_strFindFileType);        
        WriteFormatted(g_fpCheckOK,"BEGIN-------------------------------------------------%s\n",g_pStrTime);
    }
    

    /*printf("+------进入目录--->\n+[%s]\n\r",chTemPath);*/    
    WriteFormatted(g_fpLog,"+------进入目录--->\n+[%s]\n",chTemPath);
    
    HANDLE hFind=::FindFirstFile(szFind,&FindFileData);    
    
    if(INVALID_HANDLE_VALUE == hFind)        
    {
        WriteFormatted(g_fpLog,"<%s>No %s file found\n",g_pStrTime,g_strFindFileType);    
        return;
    }
    
    while(TRUE)         
    {
        //If director, visit all sub-folders
        if((FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) 
        {
            g_lCheckFileNumber++;
            if(FindFileData.cFileName[0]!='.') 
            {
                char szFile[MAX_PATH];
                strcpy(szFile,lpPath); 
                strcat(szFile,"\\");
                /*strcat(chTemPath,szFile);*/
                strcat(szFile,FindFileData.cFileName);
                VisitAllFiles(szFile);
            } 
        } 
        else
        { 
            //Judge if TYPE file
            g_lCheckFileNumber++;
            /*printf(" -%s\n",FindFileData.cFileName);*/        
            
            int len = strlen(FindFileData.cFileName);
            int iStrLen = strlen(g_strFindFileType);
            
            //除去目录,共检查文件数            
            const char *p = (char *)&FindFileData.cFileName[len-iStrLen];        
            
            //case insentive!
            if ( (0 == strcmp("*",g_strFindFileType)) || (0 == strcmp("*.*",g_strFindFileType)) )
            {
                //查看所有目录文件:
                g_lCheckOkFileNumber++;
                
                //if exe file, check it
                char strFileName[MAX_PATH];
                strcpy(strFileName,lpPath); 
                strcat(strFileName,"\\");
                strcat(strFileName,FindFileData.cFileName);
                WriteFormatted(g_fpLog,"<%s>已检查文件数:%ld,符合条件数:%ld,刚检查到的文件是:\n%s\n",
                    g_pStrTime,
                    g_lCheckFileNumber,
                    g_lCheckOkFileNumber,
                    strFileName);
                
                fprintf(g_fpCheckOK,"<%s> %s\n",
                    g_pStrTime,
                    strFileName);
            }
            
            else if ((_stricmp(p, g_strFindFileType) == 0)) 
            {
                g_lCheckOkFileNumber++;
                //if exe file, check it
                char strFileName[MAX_PATH];
                strcpy(strFileName,lpPath); 
                strcat(strFileName,"\\");
                strcat(strFileName,FindFileData.cFileName);
                
                WriteFormatted(g_fpLog,"<%s>已检查文件数:%ld,符合条件数:%ld,刚检查到的文件是:\n%s\n",
                    g_pStrTime,
                    g_lCheckFileNumber,
                    g_lCheckOkFileNumber,
                    strFileName);
                
                fprintf(g_fpCheckOK,"<%s> %s\n",
                    g_pStrTime,
                    strFileName);
                
                /* 置删除标志时,删除文件 */
                /*if (CheckWHVirus(fp))*/
                if (g_flagDeleteFile == FLAG_DELETE)
                { 
                    /*PrintLocalTime(g_pStrTime);*/
                    /*ClearVirus(fp, strFileName);*/ //fp closed in the function
                    /*printf("Virus Found! %s and cleared\r\n", strFileName);*/
                    /* 去只读 */
                    SetFileAttributes(strFileName,FILE_ATTRIBUTE_NORMAL);
                    
                    /* Long,非零表示成功,零表示失败。会设置GetLastError */
                    //if (DeleteFile(strFileName))
                    if (!remove(strFileName))
                    {
                        g_lClearFileNumber++;
                        /*printf("Delete file: %s successfully,已清除文件数:%ld.\n", strFileName,g_lClearFileNumber);*/
                        WriteFormatted(g_fpLog,"<%s>---Delete file: %s successfully,已清除文件数:%ld.\n", g_pStrTime,strFileName,g_lClearFileNumber);
                    }
                    else
                    {
                        /*printf("Delete file: %s failed!\n", strFileName);*/
                        WriteFormatted(g_fpLog,"<%s>---Delete file: %s failed!\n", g_pStrTime,strFileName); 
                    } 
                }
                
                /*system("cls");*/
                
                /*Sleep(SLEEP_SECOND);*/
            }
} 


//Find next file
if(!FindNextFile(hFind,&FindFileData))
{
    // printf("【OK,There is not %s type file in PATH %s】\n",TYPE,chTemPath);
    // fprintf(g_fpLog,"---------------->【OK,There is not %s type file any more in PATH %s】\n",TYPE,chTemPath);
    break; 
}
} 


/*GetCurSysTime(g_pStrTime);*/
/*fprintf(g_fpLog,"END---------------------------------------------------%s\n",g_pStrTime);*/

FindClose(hFind);
}


//从配置文件中读取配置信息:
//PATH:需要进行查找/删除的路径名
//TYPE:需要进行查找的文件类型名称
//DORV:是删除还是查看:0查看,1删除
void ReadConfigFromFile()
{
    FILE * fpConf = NULL;
    char strPathTemp[100];
    char strTypeTemp[10];
    /*char strCurTime[50];*/
    int flagDelOrView = 0;
    char strCfgFilePath[100];
    
    memset(strPathTemp,0,sizeof(strPathTemp));
    memset(strTypeTemp,0,sizeof(strTypeTemp));
    memset(strCfgFilePath,0,sizeof(strTypeTemp));
    
    
    GetCurrentDirectory(MAX_FIND_PATH,strCfgFilePath);
    
    if (NULL == (fpConf = fopen("config.cfg","r")))
    {
        WriteFormatted(g_fpLog,"Read config file error!!!->%s\n",strCfgFilePath);
        
        WriteFormatted(g_fpLog,"获取当前路径为:%s\n",strCfgFilePath);
        strcat(strCfgFilePath,"\\");
        strcat(strCfgFilePath,"config.cfg");
        
        if (NULL == (fpConf = fopen(strCfgFilePath,"w")))
        {
            WriteFormatted(g_fpLog,"Read config file error!!!->%s\n",strCfgFilePath);
            exit(0);
        }
    }
    
    GetCurSysTime(g_pStrTime);
    
    fscanf(fpConf,"PATH=%s\n",strPathTemp);
    fscanf(fpConf,"TYPE=%s\n",strTypeTemp);
    fscanf(fpConf,"DORV=%d\n",&flagDelOrView);
    
    WriteFormatted(g_fpLog,"\n读取的文件配置信息:\n",g_pStrTime);
    WriteFormatted(g_fpLog,"PATH=%s\n",strPathTemp);
    WriteFormatted(g_fpLog,"TYPE=%s\n",strTypeTemp);
    WriteFormatted(g_fpLog,"DORV=%d\n",flagDelOrView);
    
    if (!(strcmp(strPathTemp,"") && strcmp(strTypeTemp,"")))
    {
        WriteFormatted(g_fpLog,"\n配置为空,请修改配置文件\n");
        return;
    }
    
    strcpy(g_strFindFilePath,strPathTemp);
    strcpy(g_strFindFileType,strTypeTemp);
    g_flagDeleteFile = flagDelOrView;
    
    WriteFormatted(g_fpLog,"\n全局配置信息:\n",g_pStrTime);
    WriteFormatted(g_fpLog,"g_strFindFilePath=%s\n",g_strFindFilePath);
    WriteFormatted(g_fpLog,"g_strFindFileType=%s\n",g_strFindFileType);
    WriteFormatted(g_fpLog,"g_flagDeleteFile=%d\n",g_flagDeleteFile);
    
    fCloseFileFp(&fpConf);
    WriteFormatted(g_fpLog,"Read config successfully!!!\n");
    //Sleep(3000);
}


//保存配置到配置文件中:
//PATH:需要进行查找/删除的路径名
//TYPE:需要进行查找的文件类型名称
//DORV:是删除还是查看:0查看,1删除
void SaveConfigToFile()
{
    FILE * fpConf = NULL;
    char strPathTemp[100];
    char strTypeTemp[10];
    /*char strCurTime[50];*/
    int flagDelOrView = 0;
    
    WriteFormatted(g_fpLog,"\n保存配置信息:\n");
    
    memset(strPathTemp,0,sizeof(strPathTemp));
    memset(strTypeTemp,0,sizeof(strTypeTemp));
    
    if (NULL == (fpConf = fopen("config.cfg","w")))
    {
        WriteFormatted(g_fpLog,"Read config file error !!!\n");
        return;
    }
    
    if (!(strcmp(g_strFindFilePath,"") && strcmp(g_strFindFileType,"")))
    {
        WriteFormatted(g_fpLog,"配置为空,请重新配置\n");
        return;
    }
    
    //将配置信息打印出来 
    //保存到配置文件中
    /*fprintf(g_fpLog,"<%s>全局配置信息:\n",g_pStrTime);*/
    fprintf(fpConf,"PATH=%s\n",g_strFindFilePath);
    fprintf(fpConf,"TYPE=%s\n",g_strFindFileType);
    fprintf(fpConf,"DORV=%d\n",g_flagDeleteFile);
    
    //将保存后的信息写到日志及标准输出中
    WriteFormatted(g_fpLog,"保存配置后的配置信息:\n",g_pStrTime);
    WriteFormatted(g_fpLog,"PATH=%s\n",g_strFindFilePath);
    WriteFormatted(g_fpLog,"TYPE=%s\n",g_strFindFileType);
    WriteFormatted(g_fpLog,"DORV=%d\n",g_flagDeleteFile);
    
    fCloseFileFp(&fpConf);
    WriteFormatted(g_fpLog,"Save config successfully!!!\n");
    //Sleep(3000);
}


void ModifyCfg()
{
    char ch;
    
    while (1)
    {
        fflush(stdin);
        flushall();
        
        WriteFormatted(g_fpLog,"<%s>[m]",g_pStrTime);
        
        ch = getch();
        WriteFormatted(g_fpLog,"%c\n",ch);
        if (13 == ch)
        {
            continue;
        }
        else if ('1' == ch)
        {
            WriteFormatted(g_fpLog,"\n请输入路径:");
            scanf("%s",g_strFindFilePath);
            continue;
        }
        else if ('2' == ch)
        {
            WriteFormatted(g_fpLog,"\n请输入需要查找的文件类型:");
            scanf("%s",g_strFindFileType);
            continue;
        }    
        else if ('3' == ch)
        {
            WriteFormatted(g_fpLog,"\n请输入是查看还是删除:0:查看,2:删除\n");
            scanf("%d",&g_flagDeleteFile);
            //如果不是删除或查看的选择,默认为查看
            if ((g_flagDeleteFile != FLAG_DELETE) && (g_flagDeleteFile != FLAG_VIEW_FILE))
            {
                g_flagDeleteFile = FLAG_VIEW_FILE;
            }
            continue;
        }
        else if ('q' == ch || 'e' == ch)
        {
            //SaveConfigToFile();
            break;
        }
        else if ('s' == ch)
        {
            //保存配置到配置文件中
            SaveConfigToFile();
            /*system("dir");*/
        }
        else if ('r' == ch)
        {
            //从文件中读取配置
            ReadConfigFromFile();
            /*system("dir");*/
        }
        else if ('?' == ch || 'h' == ch)
        {
            //WriteFormatted(g_fpLog,"\n////////////////////////////////////////////////////////////////\n");
            WriteFormatted(g_fpLog,"%s\n","\n修改配置文件:\n1.路径 \n2.文件类型 \n3.删除(0-查看,2-删除) \nq,e退出\n");
            continue;
        }
        else
        {
            WriteFormatted(g_fpLog,"\nInput error,please check it.\n\n");
            continue;
        }
    }
    
    
    
    // if(!strcmp("",g_strFindFilePath) || !strcmp("",g_strFindFileType))
    // {
    // WriteFormatted(g_fpLog,"竟然不输入路径和类型,想搞死我啊!!!\n");
    // /*GetCurrentDirectory(MAX_FIND_PATH,g_strFindFilePath);*/
    // // memset(g_strFindFileType,0,10);
    // // strcpy(g_strFindFileType,"log");
    // 
    // ReadConfigFromFile();
    // }
    
    
    
    
    
#ifdef FLAG_DEBUG
    WriteFormatted(g_fpLog,
        "g_strFindFilePath:%s\n,g_strFindFileType:%s\n,g_flagDeleteFile:%d\n",
        g_strFindFilePath,
        g_strFindFileType,
        g_flagDeleteFile);
#endif //FLAG_DEBUG 
}


void My_ShellExecute( HWND hwnd,
                     LPCTSTR lpOperation,
                     LPCTSTR lpFile,
                     LPCTSTR lpParameters,
                     LPCTSTR lpDirectory,
                     INT nShowCmd
                     )
{
    HINSTANCE hRet = ShellExecute( hwnd,
        lpOperation,
        lpFile,
        lpParameters,
        lpDirectory,
        nShowCmd
        );
    int iRet = (int)hRet;
    switch(iRet)
    {
    case 0:
        WriteFormatted(g_fpLog,"The operating system is out of memory or resources.");
        break;
    case ERROR_FILE_NOT_FOUND:
        WriteFormatted(g_fpLog,"The specified file was not found.");
        break;
    case ERROR_PATH_NOT_FOUND:
        WriteFormatted(g_fpLog,"The specified file was not found.");
        break;
    case ERROR_BAD_FORMAT:
        WriteFormatted(g_fpLog,"The specified file was not found.");
        break;
    case SE_ERR_ACCESSDENIED:
        WriteFormatted(g_fpLog,"The specified file was not found.");
        break;
    case SE_ERR_ASSOCINCOMPLETE:
        WriteFormatted(g_fpLog,"The file name association is incomplete or invalid.");
        break;
    case SE_ERR_DDEBUSY:
        WriteFormatted(g_fpLog,"The Dynamic Data Exchange (DDE) transaction could not be completed because other DDE transactions were being processed.");
        break;
    case SE_ERR_DDEFAIL:
        WriteFormatted(g_fpLog,"The DDE transaction failed.");
        break;
    case SE_ERR_DDETIMEOUT:
        WriteFormatted(g_fpLog,"The DDE transaction could not be completed because the request timed out.");
        break;
    case SE_ERR_DLLNOTFOUND:
        WriteFormatted(g_fpLog,"The specified DLL was not found.");
        break;
    default:
#ifdef FLAG_DEBUG
        //失败返回值会小于或等于32
        if (iRet>32)
        {
            WriteFormatted(g_fpLog,"\n-----[Function]:My_ShellExecute successfully:%d-----\n",iRet);
        }
        else
        {
            WriteFormatted(g_fpLog,"===================Other:%d=======================",iRet);
        }
#endif //FLAG_DEBUG
        
        break;
    }
}


void FileOptions()
{
#if 0
    printf("----------------------------------------------\n");
    printf("DeleteFile.exe (argv[1]) (argv[2]) (argv[3]) :\n");
    printf("argv[1]:绝对路径名(最后不加\\\n");
    printf("argv[2]:要查找or删除的文件类型\n");
    printf("argv[3]:标志:2--删除 其它--查看\n");
#endif
    
    char ch;
    
    WriteFormatted(g_fpLog,STR_LOGO);
    
    while(1)
    {
        InitGlobalVar();
#ifdef FLAG_DEBUG
        DebugAndPrintAllGlobalVar();
#endif 
        //PRINTTOSCR(STR_HELP);
        //WriteFormatted(g_fpLog,STR_HELP);
        WriteFormatted(g_fpLog,"<%s>",g_pStrTime);
        flushall();
        fflush(stdin);
        ch = getch();
        WriteFormatted(g_fpLog,"%c\n",ch);
        
        if ('y' == ch || 'Y' == ch)
        {
            ModifyCfg(); 
            
            WriteFormatted(g_fpLog,"即将要查找%s下%s类型的文件了哦\n",g_strFindFilePath,g_strFindFileType);
            
            Sleep(3000);
            VisitAllFiles(g_strFindFilePath);
            
            //CloseOrFreeGlobalVar();
        }
        else if (ch =='q' || ch == 'e' || ch == 'Q' || ch == 'q')
        {
            int ret = MessageBoxA(NULL,"确定退出","确定退出 ",MB_YESNO);
            /*printf("--------------ret=%d-------------\n",ret);*/
            if (IDNO == ret)
            {
                WriteFormatted(g_fpLog,"<你刚才选择了否,继续>\n");
                continue;
            }
            
            WriteFormatted(g_fpLog,"<你刚才选择了是,退出>\n");
            flushall();
            //CloseOrFreeGlobalVar();
            break;
        }
        else if (ch == 'm')
        {
            ModifyCfg();
        }
        else if ('d' == ch)
        {
            DebugAndPrintAllGlobalVar();
        }
        else if ('?' == ch)
        {
            WriteFormatted(g_fpLog,STR_HELP);
        }
        else if ('r' == ch)
        {
            WriteFormatted(g_fpLog,"ExecAppByCmd..\n");
            ExecAppByCmd();
            WriteFormatted(g_fpLog,"ExecAppByCmd..Finish.\n");
        }
        else if ('s' == ch)
        {
            SaveConfigToFile();
        }
        else if ('t' == ch)
        {
            WriteFormatted(g_fpLog,"\n太懒了,这个是用做测试用的,大哥\n");
            Sleep(2000);
            ReadConfigFromFile();
            VisitAllFiles(g_strFindFilePath);
        }
        else if ('c' == ch)
        {
            //清屏
            system("cls");
        }
        else
        {
            //空格与回车,继续
            if (ch == ' ' || ch == 13)
            {
                continue;
            }
            
            WriteFormatted(g_fpLog,"Input error,please check it.\n");
        }
        
        //printf("<Enter to continue>\n");
    }
    
    //退出时,打开文件
    My_ShellExecute(NULL, "edit","OutPut.txt" , NULL, NULL, SW_SHOWNORMAL|SW_SHOWMAXIMIZED);
    CloseOrFreeGlobalVar();
    /*getch();*/
}

void ExecAppByCmd()
{
    int Ret = WinExec("I:/C_zww_projects/FileDelete/Debug/FileDelete.exe I:/C_zww_projects/FileDelete log",SW_SHOWMAXIMIZED);
    WriteFormatted(g_fpLog,"WinExec...return[%d]\n",Ret);
}

你可能感兴趣的:(Windows API 实现查找、删除任意类型的文件_VERSION20120612(vc6.0调试通过)(2012.6.12最新修改))