字符串替换

在文件夹下查找指定后缀名的文件,将文件中的某段字符串替换成指定的字符串,本段程序的作用为将后缀名为“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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值