/*
将某个文件夹中的全部文件, 按以下两条规定重命名.
一. 如果文件名中含有'_'且'_'到'.'之间只有一位数, 在这位数前面加'0'
二. 如果文件名中不含'_'且'.'前面只有一位数, 在这位数前面加'0'
程序目前存在无法解释的bug, 当pAddress的路径和old, 相同时文件名无法替换.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* pAddress = "F:\\149110\\";
char fileAddress[100];
void deleteChangeLine(char arr[100]);
void chackFileName(char fileName[50]);
void renameFunc1(char fileName[50]);
void renameFunc2(char fileName[50]);
int main()
{
char* mAddress = "G:\\dir.txt";
FILE* mFile = fopen(mAddress, "r");
char fileName[50];
system("dir F:\\149110\\ /b > G:\\dir.txt");
//使用文本中的名字找到对应的文件
while (fgets(fileName, 50, mFile) != NULL)
{
strcpy(fileAddress, pAddress);
strcat(fileAddress, fileName);
deleteChangeLine(fileAddress);
//printf("%s", fileAddress); //文件完整路径
FILE* findFile = fopen(fileAddress, "r");
if (findFile == NULL) {
printf("find file fail!");
}
//printf("secceseful find file!"); //成功找到文件
//检测文件名是否合法, 如果不合法就修改.
chackFileName(fileName);
}
return 0;
}
void deleteChangeLine(char fileAddress[100])
{
for (int i = 0; i < 100; i++)
{
if (fileAddress[i] == '\n')
{
fileAddress[i] = '\0';
}
}
}
void chackFileName(char fileName[50])
{
char fileNameCopy[50] = { 0 };
strcpy(fileNameCopy, fileName);
for (int i = 0; i < 50; i++)
{
if (fileNameCopy[i] == '_')
{
renameFunc2(fileName);
}
if (i == 49)
{
renameFunc2(fileName);
}
}
}
void renameFunc1(char fileName[50])
{
char newName[50] = { 0 };
char newFileAddress[100] = { 0 };
char old[40] = "D:\\13770\\137_1.bmp";
char new[40] = "D:\\13770\\137_01.bmp";
int j = 0;
for (int i = 0; i < 50; i++)
{
if (fileName[i] == '_')
{
newName[j] = fileName[i];
if (fileName[i + 2] == '.')
{
j++;
newName[j] = '0';
}
}
else
{
newName[j] = fileName[i];
}
j++;
}
strcpy(newFileAddress, pAddress);
strcat(newFileAddress, newName);
deleteChangeLine(newFileAddress);
//printf("%s --- %s \n", fileAddress, newFileAddress);
int result = rename(old, new);
printf("%d", result);
}
void renameFunc2(char fileName[50])
{
char old[40] = "F:\\149110\\01.bmp";
char new[40] = "F:\\149110\\1.bmp";
char newName[50] = { 0 };
char newFileAddress[100] = { 0 };
int j = 0;
for (int i = 0; i < 50; i++)
{
if (i == 0)
{
if (fileName[i + 2] == '.') {
newName[j] = '0';
}
j++;
}
newName[j] = fileName[i];
j++;
}
strcpy(newFileAddress, pAddress);
strcat(newFileAddress, newName);
deleteChangeLine(newFileAddress);
rename(old, new);
}
标签:02,遇到,处理,50,fileName,char,fileAddress,newFileAddress,newName
From: https://www.cnblogs.com/Deng-S/p/17509783.html