转换注释,从文件里哦

在一个文件里有一段代码,将里面的 /* */ 注释全部转换为 // 注释,初学者可能听起来很牛很难(我现在是初学者,我是这样认为的),只要理解了问题的意思,就会发现,诶,有点意思

话不多说,直接代码走起

convert_comment.h

#ifndef _CONVERT_COMMENT_H_
#define _CONVER_COMMENT_H_

#define INPUTFILE "input.c"
#define OUTPUTFILE "output.c"
enum{CSTATUS,CPPSTATUS,NULLSTATUS,EOFSTATUS};
void connver_main();
#endif

main.c

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include"convert_comment.h"
int main()
{
	connver_main();
	system("pause");
}

convert_comment.c

#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include"convert_comment.h"
int status = NULLSTATUS;
void do_null_status(FILE* ifp,FILE *ofp)
{
	int c = fgetc(ifp);
	switch(c)
	{
	case '/':
		{
			int s = fgetc(ifp);
			switch(s)
			{
			case '*':
				{
				fputc('/',ofp);
				fputc('/',ofp);
				status = CSTATUS;
				}
				break;
			case '/':
				fputc('/',ofp);
				fputc('/',ofp);
				status = CPPSTATUS;
				break;
			case EOF:
				status = EOFSTATUS;
				break;
			default:
				fputc(c,ofp);
				ungetc(s,ifp);//不知道啥东西,退回去
				status = NULLSTATUS;
				break;
			}
		}
		break;
	case EOF:
		status = EOFSTATUS;
		break;
	default:
		fputc(c,ofp);
		status = NULLSTATUS;
		break;
	}
}
void do_cpp_status(FILE* ifp,FILE *ofp)// is //
{
	int c = fgetc(ifp);
	switch(c)
	{
	case '\n':
		fputc('\n',ofp);
		break;
	case '/':
		status = CPPSTATUS;
		break;
	case '*':
		fputc('/',ofp);
		fputc('/',ofp);
		break;
	case EOF:
		status = EOFSTATUS;
		break;
	default:
		fputc(c,ofp);
		status = NULLSTATUS;
		break;
	}
}

void do_c_status(FILE* ifp,FILE *ofp)// is **
{
	int c = fgetc(ifp);
	switch(c)
	{
	case '*':
		{
			int s = fgetc(ifp);
			switch(s)
			{
			case '/':
				fputc('\n',ofp);
				status = NULLSTATUS;
				break;
			default:
				fputc(c,ofp);
				ungetc(s,ifp);
				status = CSTATUS;
				break;
			}
		}
		break;
	case EOF:
		status = EOFSTATUS;
		break;
	case '\n':
		fputc('\n',ofp);
		fputc('/',ofp);
		fputc('/',ofp);
		status = CSTATUS;
		break;
	default:
		fputc(c,ofp);
		status = CSTATUS;
		break;
	}
}


static void convert_work(FILE * ifp,FILE * ofp)
{
	while(status != EOFSTATUS)
	{
		switch( status)
		{
		case NULLSTATUS:
			do_null_status(ifp,ofp);
			break;
		case CPPSTATUS:
			do_cpp_status(ifp,ofp);
			break;
		case CSTATUS:
			do_c_status(ifp,ofp);
			break;
		case EOFSTATUS:
			break;
		default:
			break;

		}
	}
}

void connver_main()
{
	FILE *ifp = fopen(INPUTFILE,"r");
	FILE * ofp = fopen(OUTPUTFILE,"w");
	if(ifp == NULL||ofp == NULL)
	{
		fprintf(stderr,"this is fopen error\n");
		return ;
	}
	convert_work(ifp,ofp);

	fclose(ifp);
	fclose(ofp);
}

不要忘了要把 input.c output.c文件建立在和你main.c comment.c .h文件一样的位置哦!

如果有不对的地方,可以评论告诉我,望指导!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值