过滤源代码文件中的注释

前段时间参加一个公司面试,自己写的算法,却被说成是在网上有的算法,而且变量命名都一样。也罢!

#include "stdio.h"

int main(int argc, char const *argv[])
{
	FILE * fp;

	char* buf_old=NULL;
	char* buf_new=NULL;

	int flag=0;

	//in.c为输入文件out.c为输出文件
	char* in_file="in.c";
	char* out_file="out.c";
	fp=fopen(in_file,"rb");

	if (fp == NULL)
	{
		printf(" file open failed!");
		exit(1);
	}

	fseek(fp,0,SEEK_END);

	//printf("fp")
	int file_size = ftell(fp);
	printf("size:%d\n",file_size); 
	//文件复位
	rewind(fp);

	//分配内存大小
	buf_old=(char*)malloc(file_size);
	buf_new=(char*)malloc(file_size);

	//清空缓存区
	memset(buf_old,0,file_size);
	memset(buf_new,0,file_size);

	//指向buf_new当前写入位置
	int pcurrent=0;

	if(buf_new == NULL || buf_old == NULL)
	{
		printf("malloc error!");
		exit(1);
	}

	fread(buf_old,1,file_size,fp);

	//关闭源文件
	fclose(fp);
	fp=NULL;

	int i=0;

	/**
	*	过滤部分是采取用从流中抽取"//"---> '\n'和 "/*" ---> "* /"的方法,
	*	flag为标志位,当flag为0时,为正常状态,流进行copy,当flag为1时,为
	*	"//"状态,到'\n'结束,当flag为2时,为"/*"状态,到"* /"结束
	*/
	for(;i<file_size;i++)
	{

		if(flag == 0 && buf_old[i] == '/')
		{
			if(buf_old[i+1] == '/')
			{
				flag = 1;
				++i;
			}
			else if (buf_old[i+1] == '*')
			{
				flag = 2;
				++i;
			}
			else
			{
				buf_new[pcurrent]=buf_old[i];
				++pcurrent;
			}

		}
		else if (flag == 1)
		{
			if(buf_old[i] == '\n')
			{
				flag=0;

				if(pcurrent > 0 && buf_new[pcurrent-1] != '\n')
				{ //防止因为"//"开头的注释位于非单独的一行时,照成后面的语句直接跟到这一行来,造成格式混乱!
					buf_new[pcurrent]='\n';
					++pcurrent;
				}
			}
			
		}
		else if (flag == 2)
		{
			if(buf_old[i] == '*'&& buf_old[i+1] == '/')
			{
				flag = 0;
				++i;
			}
		}
		else
		{
			buf_new[pcurrent]=buf_old[i];
			++pcurrent;
		}

	}

	//后面为重新写入文件部分,简略过去
	FILE * fout;

	fout = fopen(out_file,"wb");

	fwrite(buf_new,1,pcurrent,fout);

	fclose(fout);
	fout = NULL;

	//释放在堆中申请的内存
	free buf_new;
	free buf_old;

	return 0;
}

有需要的可以参考一下,不足之处,可以帮忙指正。谢谢

转载于:https://my.oschina.net/wxwHome/blog/76817

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值