#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<direct.h>
#include <io.h>

int strreplace(char *outstr, const char *str, const char *oldstr, const char *newstr)
{
    char bstr[300];
    memset(bstr, 0, sizeof(bstr));
    int i = 0;
    for (i = 0; i < strlen(str); i++) {
        if (!strncmp(str + i, oldstr, strlen(oldstr))) {
            strcat(bstr, newstr);
            i += strlen(oldstr) - 1;
        }
        else {
            strncat(bstr, str + i, 1);
        }
    }

    strcpy(outstr, bstr);
    return 0;
}

void changeAllFileName(const char* path, const char* oldName, const char* newName) {
    long hFile = 0;

    //文件信息读取结构
    struct _finddata_t fileinfo;
    char findMatch[200] = { 0 };
    int pathLen = strlen(path);
    strcpy(findMatch, path);
    strcat(findMatch, "\\");
    strcat(findMatch, "*");

    if ((hFile = _findfirst(findMatch, &fileinfo)) != -1) {
        do {
            //类型是否是文件夹
            if (~fileinfo.attrib & _A_SUBDIR) {
                char temp1[300] = { 0 };
                char temp2[300] = { 0 };

                strcpy(temp1, path);
                strcat(temp1 + pathLen, "\\");
                strcat(temp1 + pathLen, fileinfo.name);

                strcpy(temp2, temp1);
                strreplace(temp2 + pathLen + 1, fileinfo.name, oldName, newName);

                int flag = rename(temp1, temp2);
                printf("%s -> %s (%x)\n", fileinfo.name, temp2 + pathLen, flag);
            }
            //下一个,成功返回0,否则-1
        } while (!_findnext(hFile, &fileinfo));
        _findclose(hFile);
    }
}

int main()
{
    const char dir[512] = { 0 };
    const char source[512] = { 0 };
    const char dest[512] = { 0 };

    printf("输入文件目录:"); scanf("%s", dir);
    printf("源名字:"); scanf("%s", source);
    printf("目标名字:"); scanf("%s", dest);

    changeAllFileName(dir, source, dest);
    system("PAUSE");
    return 0;
}