======================================================================================================================================================
注释转换
原理图:
这张状态图很完美的说明了一切情况,以这张图为框架来具体实现注释装换代码。
代码如下:
//convert.h
#ifndef __CONVERT_H__
#define __CONVERT_H__
#include<stdio.h>
typedef enum STATE
{
NUL_STATE,
C_STATE,
CPP_STATE,
END_STATE
}STATE;
void DealConvertwork(FILE* pfin, FILE* pfout);
void Dealnul_state(FILE* pfin, FILE* pfout, STATE* p);
void Dealc_state(FILE* pfin, FILE* pfout, STATE* p);
void Dealcpp_state(FILE* pfin, FILE* pfout, STATE* p);
#endif
//convert.c
#include<stdio.h>
#include"convert.h"
void DealConvertwork(FILE* pfin, FILE* pfout)//状态机的总体框架
{
STATE state = NUL_STATE;
while (state != END_STATE)
{
switch (state)
{
case NUL_STATE:
Dealnul_state(pfin, pfout, &state);
break;
case C_STATE:
Dealc_state(pfin, pfout, &state);
break;
case CPP_STATE:
Dealcpp_state(pfin, pfout, &state);
break;
default:
END_STATE;
break;
}
}
}
void Dealnul_state(FILE* pfin, FILE* pfout, STATE* p)//对空状态的处理
{
int first = fgetc(pfin);
switch (first)
{
case '/':{
int second = fgetc(pfin);
switch (second)
{
case '*':{
fputc('/', pfout);
fputc('/', pfout);
*p = C_STATE;
}
break;
case '/':{
fputc(first, pfout);
fputc(second, pfout);
*p = CPP_STATE;
}
break;
default:
fputc(first, pfout);
fputc(second, pfout);
break;
}
}
break;
case EOF:
*p = END_STATE;
break;
default:
fputc(first, pfout);
break;
}
}
void Dealc_state(FILE* pfin, FILE* pfout, STATE* p)//处理c状态
{
int first = fgetc(pfin);
switch (first)
{
case '*':{
int second = fgetc(pfin);
switch (second)
{
case '/':{
int third = fgetc(pfin);
}
fputc('\n', pfout);
*p = NUL_STATE;
break;
case '*':
ungetc(second, pfin);
fputc(first, pfout);
break;
default:
fputc(first, pfout);
fputc(second, pfout);
break;
}
}
break;
case '\n':
fputc('\n', pfout);
fputc('/', pfout);
fputc('/', pfout);
break;
default:
fputc(first, pfout);
break;
}
}
void Dealcpp_state(FILE* pfin, FILE* pfout, STATE* p)//处理c++状态
{
int first = fgetc(pfin);
switch (first)
{
case '\n':
fputc('\n', pfout);
*p = NUL_STATE;
break;
case EOF:
*p = END_STATE;
break;
default:
fputc(first, pfout);
break;
}
}
//test.c
#define _CRT_SECURE_NO_DEPRECATE 1
#include<stdio.h>
#include<errno.h>
#include<stdlib.h>
#include<windows.h>
#include"convert.h"
int main()
{
FILE* pfin = fopen("input.c", "r");//打开文件
FILE* pfout = fopen("output.c", "w");
if (pfin == NULL)
{
perror("open for read");
exit(EXIT_FAILURE);
}
if (pfout == NULL)//如果打开失败则关闭已被打开的待转换文件
{
fclose(pfin);
perror("open for write");
exit(EXIT_FAILURE);
}
DealConvertwork(pfin, pfout);
fclose(pfin);//最后统一关闭打开的文件
fclose(pfout);
system("pause");
return 0;
}
总结
- 1,这是一次状态机的实例应用;
- 2,有时杂乱无章的代码实现用状态机可能相对简单一些,把该有的状态列举出来,分析转换状态。这样考虑问题也会全面一些,有限状态机非常实用。
================================================================================