删注释

#include <stdio.h>
#include <io.h>
#include <string.h>
enum CommentType{
	None = 0,
	LineComment,
	BlockComment
};

void RemoveComments(char* src, int srclen, char* &dst, int &dstlen)
{
	int len = srclen;
	dst = new char[len + 1];
	int i = 0;
	int j = 0;
	bool isComment = false;
	CommentType currentType;
	while (i < len+1)
	{
		if (isComment)
		{
			if (currentType == BlockComment && src[i] == '*' && src[i+1] == '/')
			{
				isComment = false;
				currentType = None;
				i += 2;
				dst[j] = '\n';
				++j;
				continue;
			}else if (currentType == LineComment && src[i] == '\n' )
			{
				isComment = false;
				currentType = None;
				++i;
				dst[j] = '\n';
				++j;
				continue;
			}else{
				++i;
				continue;
			}
		}else{
			if ( src[i] == '/' && src[i+1] == '/')
			{
				isComment = true;
				currentType = LineComment;
				i += 2;
				continue;
			}else if (src[i] == '/' && src[i+1] == '*'){
				isComment = true;
				currentType = BlockComment;
				i += 2;;
				continue;
			}else if(src[i] == '\n' && src[i+1] == '\n'){
				++i;
				continue;
			}else if(src[i] == '\n' && j > 1 && dst[j-1] == '\n'){
				++i;
				continue;
			}else{
				dst[j] = src[i];
				++j;
				++i;
			}
		}		
	}
	dstlen = j-1;
}

int main(int argc, char** argv)
{
	if (argc < 3)
	{
		return 0;
	}
	if (_access(argv[1], 0) != 0)
	{
		return 0;
	}
	FILE* pf = fopen(argv[1], "rb");
	fseek(pf, 0, SEEK_SET);
	long xs = ftell(pf);
	fseek(pf, 0, SEEK_END);
	long xlen = ftell(pf) - xs;
	char* src = new char[xlen];
	fseek(pf, 0, SEEK_SET);
	fread(src, xlen, 1, pf);
	char* dstbuf;
	int dlen;
	RemoveComments(src, xlen, dstbuf, dlen);	
	FILE* pfx = fopen(argv[2], "wb+");
	fwrite(dstbuf, dlen, 1, pfx);

	delete[] src;
	delete[] dstbuf;
	fclose(pf);
	fclose(pfx);

	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值