标签:c程序 注释转换 c++
#define _CRT_SECURE_NO_WARNINGS 1
#include"CommentConvert.h"
StateType state;
void DoNullState(FILE *read, FILE *write)
{
int first = fgetc(read);
int second = 0;
switch (first)
{
case ‘/‘:
second = fgetc(read);
if (second == ‘*‘)
{
fputc(first, write);
fputc(‘/‘, write);
state = C_STATE;
}
else if (second == ‘/‘)
{
fputc(first, write);
fputc(second, write);
state = CPP_STATE;
}
else
{
fputc(first, write);
fputc(second, write);
}
break;
case EOF:
fputc(first,write);
state = END_STATE;
default:
fputc(first, write);
break;
}
}
void DoCState(FILE *read, FILE *write)
{
int first = fgetc(read);
int second = 0;
switch (first)
{
case ‘*‘:
second = fgetc(read);
if (second == ‘/‘) //舍弃*/
{
int third = 0;
third = fgetc(read);
if (third != ‘\n‘&&third != EOF)
{
fseek(read, -1, SEEK_CUR);
fputc(‘\n‘, write);
}
else
{
fputc(‘\n‘, write);
}
state = NULL_STATE;
}
else if (second == ‘*‘)
{
ungetc(second, read);
fputc(first, write);
}
else
{
fputc(first, write);
fputc(second, write);
}
break;
case ‘\n‘:
fputc(first, write);
fputc(‘/‘, write);
fputc(‘/‘, write);
break;
case EOF:
fputc(first,write);
state = END_STATE;
break;
default:
fputc(first, write);
break;
}
}
void DoCppState(FILE *read, FILE *write)
{
int first = fgetc(read);
int second = 0;
switch (first)
{
case ‘\n‘:
fputc(first, write);
state = NULL_STATE;
break;
case EOF:
state = END_STATE;
break;
default:
fputc(first, write);
break;
}
}
void ConvertWork(FILE *read, FILE *write)
{
state = NULL_STATE;
while (state != END_STATE)
{
switch (state)
{
case NULL_STATE:
DoNullState(read, write);
break;
case C_STATE:
DoCState(read, write);
break;
case CPP_STATE:
DoCppState(read, write);
break;
}
}
}
void CommentConvert()
{
FILE* pWrite = NULL;
FILE* pRead = fopen(INPUTFILENAME, "r");
if(pRead == NULL)
{
perror("open file for read");
exit(EXIT_FAILURE);
}
pWrite = fopen(OUTPUTFILENAME, "w");
if (pWrite == NULL)
{
fclose(pRead);
perror("open file for write");
exit(EXIT_FAILURE);
}
ConvertWork(pRead,pWrite); //转换函数
fclose(pRead);
fclose(pWrite);
}
input.c
output.c
利用状态机把此问题中涉及的分为3个状态,即C状态,C++状态,NULL状态,当遍历到某一个\n,/*,//时,要分情况这三个状态之间转换
标签:c程序 注释转换 c++
原文地址:http://10921020.blog.51cto.com/10911020/1753289