注释转换是指将input.c程序中C语言注释全部转化为C++注释,并在output.c中展现出来
可能出现的情况如下图所示
代码实现如下:
test,c
#include "Comment Covert.h"
#include<stdlib.h>
int main()
{
FILE *pfRead = NULL;
FILE *pfWrite = NULL;
pfRead = fopen("input.c", "r");
if (NULL == pfRead)
{
perror("open file for read");
return;
}
pfWrite = fopen("output.c", "w");
if (NULL == pfWrite)
{
perror("open file for write");
fclose(pfRead);
return;
}
DoConvertWork(pfRead, pfWrite);
fclose(pfRead);
fclose(pfWrite);
system("pause\n");
return 0;
}
Commet Covert.h中
#define _CRT_SECURE_NO_WARNINGS 1
#ifndef __COMMNT_H__
#define __COMMNT_H__
#include<stdio.h>
enum STATE
{
NUL_STATE,
C_STATE,
CPP_STATE,
END_STATE
};
void DoCState(FILE *pfIn, FILE *pfOut);
void DoCPPState(FILE *pfIn, FILE *pfOut);
void DoNulState(FILE *pfIn, FILE *pfOut);
void DoConvertWork(FILE *pfIn, FILE *pfOut);
#endif // __COMMNT_H__
Comment Convert.c中
#include"Comment Covert.h"
static enum STATE state = NUL_STATE;
void DoConvertWork(FILE *pfIn, FILE *pfOut)
{
while (state != END_STATE)
{
switch (state)
{
case C_STATE:
DoCState(pfIn, pfOut);
break;
case CPP_STATE:
DoCPPState(pfIn, pfOut);
break;
case NUL_STATE:
DoNulState(pfIn, pfOut);
break;
}
}
}
void DoNulState(FILE *pfIn, FILE *pfOut)
{
int first = fgetc(pfIn);
switch (first)
{
case '/':
{
int second = fgetc(pfIn);
switch (second)
{
case '*':
fputc('/', pfOut);
fputc('/', pfOut);
state = C_STATE;//C风格开始
break;
case '/':
fputc(first, pfOut);
fputc(second, pfOut);
state = CPP_STATE;//C++风格开始
break;
default:
fputc(second, pfOut);
break;
}
break;
}
case EOF:
state = END_STATE;
break;
default:
fputc(first, pfOut);
}
}
void DoCState(FILE *pfIn, FILE *pfOut)//C转换为Cpp;
{
int first = fgetc(pfIn);
int second = 0;
switch (first)
{
case '*':
second = fgetc(pfIn);
if (second == '/')//舍弃 */;
{
int third = fgetc(pfIn);
state = NUL_STATE;
if (third != '\n')
{
fputc('\n', pfOut);
ungetc(third, pfIn);//ungetc函数的功能是将已读数据还回缓冲区;
}
if (third == '\n')
{
fputc(third, pfOut);
}
}
else
{
fputc(first, pfOut);
ungetc(second, pfIn);//将*之后的内容还回缓冲区;
}
break;
case '\n'://如果是换行,那就是连续注释,就将下一行开头加入Cpp注释;
fputc(first, pfOut);
fputc('/', pfOut);
fputc('/',pfOut );
break;
case EOF:
fputc(first, pfOut);
state = END_STATE;
break;
default:
fputc(first, pfOut);
break;
}
}
void DoCPPState(FILE *pfIn, FILE *pfOut)
{
int first = fgetc(pfIn);
switch (first)
{
case '\n':
fputc(first, pfOut);
state = NUL_STATE;
break;
case EOF:
state = END_STATE;
default:
fputc(first, pfOut);
break;
}
}
input.c
// 1.一般情况
int num = 0;
/* int i = 0; */
// 2.换行问题
/* int i = 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.连续注释问题
/*a*//*b*/
// 6.连续的**/问题
/***/
// 7.C++注释问题
/*xxxxxxxxxxxx*/
输出结果对比如下