首先要将文本分成四个状态:
1.普通状态(NULLSTATUS)
2.c状态(CSTATUS)
3.cpp状态(CPSTATUS)
4.EOF状态(EOFSTATUS)
四个状态之间的关系如下:
程序代码如下:
main.c
#include"convert.h"
int main()
{
convert_main();
//测试驱动开发
return 0;
}
convert.h
#ifndef __COVERT_H__
#define __COVERT_H__
#include<stdio.h>
#include<stdlib.h>
#define INPUTFILE "input.c"
#define OUTPUTFILE "output.c"
enum{ CSTATUS, CPSTATUS, NULLSTATUS, EOFSTATUS };
void convert_main();
#endif
convert.c
#include"convert.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('\n', ofp);
fputc('/', ofp);
fputc('/', ofp);
status = CPSTATUS;
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)
{
int c = fgetc(ifp);
switch (c)
{
case '\n':
fputc(c, ofp);
status = NULLSTATUS;
break;
case EOF:
status = EOFSTATUS;
break;
default:
fputc(c, ofp);
status = CPSTATUS;
break;
}
}
void do_c_status(FILE *ifp, FILE *ofp)
{
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(c, 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 CPSTATUS:
do_cpp_status(ifp, ofp);
break;
case CSTATUS:
do_c_status(ifp, ofp);
break;
case EOFSTATUS:
break;
default:
break;
}
}
}
void convert_main()
{
FILE *ifp = fopen(INPUTFILE, "r");
FILE *ofp = fopen(OUTPUTFILE, "w");
if (ifp == NULL || ofp == NULL)
{
fprintf(stderr, "this is fopen err!");
return;
}
convert_work(ifp, ofp);
fclose(ifp);
fclose(ofp);
}
测试用例 input.c的内容:
// 1.一般情况
int num = 0;
/* int i = 0; */
// 2.换⾏问题
/* int i = 0; */int j = 0;
/* int i = 0; */
int j = 0;
// 3.匹配问题
/*int i = 0;/*xxxxx*/
// 4.多行注释问题
/*
int i=0;
int j = 0;
int k = 0;
*/int k = 0;
// 5.连续注释问题
/*int a = 0;*//*int b = 0;*/
// 6.连续的**/问题
/***/
// 7.C++注释问题
// /*xxxxxxxxxxxx*/
程序运行之后,output.c的内容:
// 1.一般情况
int num = 0;
// int i = 0;
// 2.换⾏问题
// int i = 0;
int j = 0;
// int i = 0;
int j = 0;
// 3.匹配问题
//int i = 0;/*xxxxx
// 4.多行注释问题
//
//int i=0;
//int j = 0;
//int k = 0;
//
int k = 0;
// 5.连续注释问题
//int a = 0;
//int b = 0;
// 6.连续的**/问题
//*
// 7.C++注释问题
// /*xxxxxxxxxxxx*/