69,382
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#include <tchar.h>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
#include <windows.h>
vector<string> g_vstrFilename; // 原始文件名
vector<string> g_vstrNewName; // 新文件名
// 读取INI文件,注意文件名的对应关系
int ReadIniFile()
{
int count = 0;
g_vstrFilename.push_back("1.dat");
g_vstrNewName.push_back("1.doc");
count++;
g_vstrFilename.push_back("2.dat");
g_vstrNewName.push_back("2.doc");
count++;
g_vstrFilename.push_back("3.dat");
g_vstrNewName.push_back("3.doc");
count++;
g_vstrFilename.push_back("4.dat");
g_vstrNewName.push_back("4.doc");
count++;
return count;
}
BOOL GetNewName(string strOldName, string& strNewName)
{
//ASSET(!g_vstrFilename.empty());
//ASSET(g_vstrFilename.empty() == g_vstrNewName.size());
vector<string>::const_iterator itr = find(g_vstrFilename.begin(), g_vstrFilename.end(), strOldName);
if(itr == g_vstrFilename.end())
{
strNewName = "";
return FALSE;
}
strNewName = g_vstrNewName[itr - g_vstrFilename.begin()];
return TRUE;
}
// 查找并更新文件名,没有对文件夹进行操作,若需要可简单递归实现
BOOL RenameFile(string strDir)
{
string strFileFilter;
HANDLE hFind = NULL;
WIN32_FIND_DATA fileinfo;
strDir += "\\";
strFileFilter = strDir + "*.dat";
string strNewName;
hFind = FindFirstFile( strFileFilter.c_str(), &fileinfo );
do {
// 暂时不对文件夹进行操作
if(!(fileinfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
{
if(GetNewName(fileinfo.cFileName, strNewName))
{
rename((strDir + fileinfo.cFileName).c_str(), (strDir + strNewName).c_str());
}
}
} while( FindNextFile( hFind, &fileinfo ) );
FindClose(hFind);
return TRUE;
}
int main()
{
ReadIniFile();
RenameFile("D:\\temp");
return 0;
}
#include <stdio.h>
#include <io.h>
#include <stdlib.h>
//判断文件是否存在,如果存在则重命名
int isExist(char *filename)
{
return (access(filename, 0) == 0);
}
int main(void)
{
int i,j;
char line[100];
//读ini文件
FILE *fp = fopen("c:\\test.ini","r");
if(fp == NULL)
{
printf("file open failed!\n");
return 0;
}
char oldName[100],newName[100];
while(fgets(line, 100, fp))
{
//取出oldName,newName以逗号分开
i = 0;
j = 0;
while(line[i] != ',')
{
oldName[j] = line[i];
++i;
++j;
}
++i;
oldName[j] = '\0';
j = 0;
while(line[i] != '\0')
{
newName[j] = line[i];
++i;
++j;
}
newName[j] = '\0';
char cmd[100];
if(isExist(oldName))//当前文件夹下存在该文件名
{
//重命名
sprintf(cmd,"ren %s %s",oldName,newName);
printf("cmd: %s\n",cmd);
if(system(cmd) != 0)
{
printf("rename failed!\n");
}
}
}
return 0;
}