将一个C源文件中的单独占行的注释删除(即该行除了注释没有其它内容),并将结果输出到另一个文件中。不考虑注释嵌套情况。

【输入形式】

从file.in文件中读入该C语言源程序,源文件不超过100行,每行不超过100个字符。

【输出形式】

将删除要求注释的文件写入file.out文件中

void MOVE(char str3[], int sz3, int stop, int k)//sz2<sz1
{
	int i = 0;
	int j = 0;
	int n = 0;
	for (j = k + (-stop)+1; j < sz3; j++)//左移
	{
		str3[j + stop] =str3[j] ;
		str3[j] = '\0';
	}
}
void move(char str[],int sz3,int stop,int k)//sz2>sz1
{
	int i = 0;
	int j = 0;
	int n = 0;

		for (j = sz3 + stop - 1; j > k+stop ; j--)
		{
			//改变str3的值
			str[j] = str[sz3 -1 - n];
			n++;
		}
}
int judge(char str1[],char str3[], int sz1, int i)
{
	int j = 0;
	for (j = 0; j < sz1; j++)
	{
		if (str1[j] == str3[i] || str1[j] == str3[i] + 32 || str1[j] == str3[i] - 32)//不分大小写
		{

		}
		else
		{
			break;
		}
		i++;
	}
	//如果相等返回1,如果不相等返回-1
	if (j == sz1)
		return 1;
	else
		return -1;
}
void replace(char str2[],char str3[],int sz2,int* i)
{
	int n = (*i);
	int j = 0;
	for (j=0; (*i)< sz2 + n; (*i)++,j++)
	{
		str3[*i] = str2[j];
	}
	(*i)--;
}
int main()
{
	//1、创建文件指针
	//2、打开文件
	//3、输入数据
	//3.5、读入数据
	//4、数据处理(替换)
	//4.5、读出数据
	//5、关闭文件
	int i = 0;
	int k = 0;
	int j = 0;
	char str1[100] = "\0";//被替换的字符串
	char str2[100] = "\0";//替换字符串
	char str3[200] = "\0";
	FILE* fpin, * fpout;//创建文件指针
	if ((fpin = fopen("filein.txt", "r")) == NULL)
	{
		printf("cannot open file");
		exit(0);
	}
	//打卡文件
	if ((fpout = fopen("fileout.txt", "w")) == NULL)
	{
		printf("cannot open file");
		exit(0);
	}
	//输入被替换和替换字符串
	scanf("%s%s", str1, str2);
	fread(str3, sizeof(char), 200, fpin);//从文件fpin中读入数据到数组str3
	//数据处理
	int sz1 = strlen(str1);
	int sz2 = strlen(str2);
	int sz3 = strlen(str3);
	int ju = 0;
	//后退sz2-sz1格
	for (i = 0; i < sz3; i++)
	{
		//判断是否相等
		ju=judge(str1, str3, sz1, i);
		if (ju==1)//相等
		{
			if (sz2 > sz1) 
			{
				//移动一次,改变一次sz3的值//要判断sz1和sz2的大小
				move(str3, sz3, sz2 - sz1, i);
			}
			else if(sz2<sz1)
			{
				MOVE(str3, sz3, sz2 - sz1, i);
			}
			else
			{

			}
			sz3 += (sz2 - sz1);
            //替换,改变i
			replace(str2,str3,sz2,&i);
		}	
	}
	fwrite(str3, sizeof(str3[0]), 200, fpout);
	fclose(fpin);
	fclose(fpout);
	return 0;
}

更多推荐