在文件夹下查找指定后缀名的文件,将文件中的某段字符串替换成指定的字符串,本段程序的作用为将后缀名为“atlas”的文件中“.png”替换成“.pvr.ccz”
#include <stdio.h>
#include <io.h>
#include <string.h>
#define MAX 1024
int replace(char *s, char *src, char *dest)
{
int i = 0;
int j = 0;
int k = 0;
int offset = 0;
int start = 0;
int flag = 0;
int len_src = strlen(src);
int len_dest = strlen(dest);
char temp[MAX];
while (s[i] != '\0' || 0 != offset)
{
if (offset < len_src && s[i] != '\0' && s[i] == src[offset])
{
offset++;
if (offset == 1)
{
start = i;
}
}
else
{
if (len_src == offset)
{
flag = 1;
k = 0;
while (k < len_dest)
{
temp[j] = dest[k];
j++;
k++;
}
offset = 0;
}
else if (offset > 0 && offset < len_src)
{
k = 0;
while (k < offset)
{
temp[j + k] = src[k];
j++;
k++;
}
offset = 0;
}
temp[j++] = s[i];
}
i++;
}
temp[j] = '\0';
if (1 == flag)
{
strcpy(s, temp);
}
return flag;
}
int deal(char *fileName)
{
FILE *temp, *handle;
char src[] = ".png";
char dest[] = ".pvr.ccz";
char str[MAX];
int flag = 0;
temp = tmpfile();
handle = fopen(fileName, "r+");
if (temp != NULL && handle != NULL)
{
while (NULL != fgets(str, MAX, handle))
{
if (1 == replace(str, src, dest))
{
flag = 1;
}
fputs(str, temp);
}
if (1 == flag)
{
fseek(temp, 0, SEEK_SET);
fseek(handle, 0, SEEK_SET);
while (NULL != fgets(str, MAX, temp))
{
fputs(str, handle);
}
}
fclose(temp);
fclose(handle);
return flag;
}
else
{
return 0;
}
}
int main(void)
{
struct _finddata_t file;
long handle;
char dest[] = "*.atlas";
if ((handle = _findfirst(dest, &file)) != EOF)
{
do
{
if (1 == deal(file.name))
{
printf("%s\n", file.name);
}
} while (EOF != _findnext(handle, &file));
}
_findclose(handle);
printf("Press any key to continue.");
getchar();
return 0;
}