一、分析题目:本题关键在于几种状态的转换,我们可以简单分为如图几种状态
有了这个图解我们就可以轻松撸代码了
二、代码展示:(多文件)
1、头文件
#ifndef __REVERSE_H__
#define __REVERSE_H__
#include <stdio.h>
void reverse_comment(FILE *ifp,FILE *ofp); //注释函数
void do_null_status(FILE *ifp,FILE *ofp); //普通状态
void do_cpp_status(FILE *ifp,FILE *ofp); //cpp状态
void do_c_status(FILE *ifp,FILE *ofp); //c状态
#endif//__REVERSE_H__
2、主函数
#define _CRT_SECURE_NO_WARNINGS 1
#include "reverse.h"
int main()
{
FILE *ifp;
FILE *ofp;
ifp=fopen("input.c","r");
ofp=fopen("output.c","w");
if (NULL==ifp || NULL==ofp)
{
printf("open err !\n");
}
else
{
reverse_comment(ifp,ofp);
}
fclose(ifp);
fclose(ofp);
return 0;
}
3、注释转换函数
#include "reverse.h"
//枚举几种状态
enum
{
NULLSTATUS,
CSTATUS,
CPPSTATUS,
EOFSTATUS
};
int status = NULLSTATUS;
void reverse_comment(FILE *ifp,FILE *ofp) //注释函数
{
while (status!=EOFSTATUS)
{
switch (status)
{
case CSTATUS:
{
do_c_status(ifp,ofp);
break;
}
case CPPSTATUS:
{
do_cpp_status(ifp,ofp);
break;
}
case NULLSTATUS:
{
do_null_status(ifp,ofp);
break;
}
case EOFSTATUS:
break;
default:
break;
}
}
}
void do_null_status(FILE *ifp,FILE *ofp) //普通状态注释
{
int ch = 0;
int c = 0;
ch = fgetc(ifp);
if (ch=='/')
{
c=fgetc(ifp);
if (c=='*')
{
fputc('/',ofp);
fputc('/',ofp);
status=CSTATUS;
}
else if (c=='/')
{
fputc('/',ofp);
fputc('/',ofp);
status=CPPSTATUS;
}
else if (c==EOF)
{
status=EOFSTATUS;
}
else
{
//ungetc(c,ifp);
fputc('/',ofp);
fputc(c,ofp);
status=NULLSTATUS;
}
}
else if (ch==EOF)
{
status=EOFSTATUS;
}
else
{
fputc(ch,ofp);
status=NULLSTATUS;
}
}
void do_cpp_status(FILE *ifp,FILE *ofp) //cpp状态注释
{
int ch = 0;
ch = fgetc(ifp);
if (ch=='\n')
{
fputc('\n',ofp);
status=NULLSTATUS;
}
else if(ch==EOF)
{
status=EOFSTATUS;
}
else
{
fputc(ch,ofp);
status=NULLSTATUS;
}
}
void do_c_status(FILE *ifp,FILE *ofp) //c状态注释
{
int ch = 0;
int c = 0;
ch=fgetc(ifp);
if (ch=='\n')
{
fputc('\n',ofp);
fputc('/',ofp);
fputc('/',ofp);
status=CSTATUS;
}
else if (ch=='*')
{
c = fgetc(ifp);
if (c=='/')
{
fputc('\n',ofp);
fputc('\t',ofp);
status=NULLSTATUS;
}
else
{
fputc(c,ofp);
//ungetc(c,ifp);
status=NULLSTATUS;
}
}
else if (ch=='\n')
{
fputc('\n',ofp);
fputc('/',ofp);
fputc('/',ofp);
status=CSTATUS;
}
else if (ch==EOF)
{
status=EOFSTATUS;
}
else
{
fputc(ch,ofp);
status=CSTATUS;
}
}
四、结果展示