* 状态基思想*
主函数
#define _CRT_SECURE_NO_WARNINGS
#include"CommentConvert.h"
void test()
{
FILE *pfRead = NULL;
FILE *pfWrite = NULL;
pfRead = fopen("input.c", "r");
if (pfRead == NULL)
{
perror("open file for read");
exit(EXIT_FAILURE);
}
pfWrite = fopen("ouput.c", "w");
if (pfWrite == NULL)
{
perror("open file for write");
fclose(pfRead);
pfRead = NULL;
exit(EXIT_FAILURE);
}
//注释转换
CommentConvert(pfRead, pfWrite);
printf("转换完成\n");
fclose(pfRead);
fclose(pfWrite);
pfRead = NULL;
pfWrite = NULL;
}
int main()
{
test();
system("pause");
return 0;
}
CommentConvert.h
文件
#define _CRT_SECURE_NO_WARNINGS
#ifndef __COMMENTCONVERT_H__
#define __COMMENTCONVERT_H__
//#pragma once
#include<stdio.h>
#include<stdlib.h>
//状态基编程
typedef enum State
{
NUL_STATE,
C_STATE,
CPP_STATE,
END_STATE
}State;
void CommentConvert(FILE *pfRead, FILE *pfWrite);
void DoNulState(FILE *pfRead, FILE *pfWrite, State *ps);
void DoCState(FILE *pfRead, FILE *pfWrite, State *ps);
void DoCppState(FILE *pfRead, FILE *pfWrite, State *ps);
#endif //__COMMENTCONVERT_H__
CommentConvert.c
文件
#define _CRT_SECURE_NO_WARNINGS
#include"CommentConvert.h"
void CommentConvert(FILE *pfRead, FILE *pfWrite)
{
State state = NUL_STATE;
while (state != END_STATE)
{
switch (state)
{
case NUL_STATE:
DoNulState(pfRead,pfWrite,&state);
break;
case C_STATE:
DoCState(pfRead, pfWrite, &state);
break;
case CPP_STATE:
DoCppState(pfRead, pfWrite, &state);
break;
}
}
}
void DoNulState(FILE *pfRead, FILE *pfWrite, State *ps)
{
int first = fgetc(pfRead);
switch (first)
{
case '/':
{
int second = fgetc(pfRead);
switch (second)
{
case '*':
{
*ps = C_STATE;
fputc('/', pfWrite);
fputc('/', pfWrite);
}
break;
case '/':
{
*ps = CPP_STATE;
fputc(first, pfWrite);
fputc(second, pfWrite);
}
break;
default:
{
fputc(first, pfWrite);
fputc(second, pfWrite);
}
break;
}
}
break;
case EOF:
*ps = END_STATE;
break;
default:
fputc(first, pfWrite);
break;
}
}
void DoCState(FILE *pfRead, FILE *pfWrite, State *ps)
{
int first = fgetc(pfRead);
switch (first)
{
case '*':
{
int second = fgetc(pfRead);
switch (second)
{
case '/':
{
//多个换行,连续注释
int third = fgetc(pfRead);
switch (third)
{
case '\n':
{
fputc(third, pfWrite);
*ps = NUL_STATE;
}
break;
case '/':
{
fputc('\n', pfWrite);
ungetc(third, pfRead);
*ps = NUL_STATE;
}
break;
default:
{
fputc('\n', pfWrite);
fputc(third, pfWrite);
*ps = NUL_STATE;
}
break;
}
}
break;
case '*':
{
// * 的送回
fputc(first, pfWrite);
ungetc(second, pfRead);
}
break;
default:
{
fputc(first, pfWrite);
fputc(second, pfWrite);
}
break;
}
}
break;
case '\n':
{
fputc(first, pfWrite);
fputc('/', pfWrite);
fputc('/', pfWrite);
}
break;
default:
fputc(first, pfWrite);
break;
}
}
void DoCppState(FILE *pfRead, FILE *pfWrite, State *ps)
{
int first = fgetc(pfRead);
switch (first)
{
case '\n':
{
*ps = NUL_STATE;
fputc('\n', pfWrite);
}
break;
case EOF:
{
*ps = END_STATE;
}
break;
default:
fputc(first, pfWrite);
break;
}
}