【C语言】注释转换(C语言->C++)

时间:2022-03-25 01:33:02

【C语言】注释转换(C语言->C++)

代码如下


.h文件

#ifndef __COMMENT_CONVERT__
#define __COMMENT_CONVERT__

#include <stdlib.h>
#include <stdio.h>

enum STATE
{
NUL_STATE,
C_STATE,
CPP_STATE,
END_STATE,
};

void DoConvertWork(FILE *pfIn, FILE *pfOut);
void DoNulState(FILE *pfIn, FILE *pfOut);
void DoCState(FILE *pfIn, FILE *pfOut);
void DoCppState(FILE *pfIn, FILE *pfOut);

#endif

text.c文件

#include <stdlib.h>
#include <Windows.h>
#include "CommentConvert.h"

void text()
{
FILE *pfIn = fopen("input.c", "r");
if (NULL == pfIn)
{
perror("open file for read");
exit(EXIT_FAILURE);
}
FILE *pfOut = fopen("output.c", "a");
if (NULL == pfOut)
{
perror("open file for write");
fclose(pfIn);
exit(EXIT_FAILURE);
}

DoConvertWork(pfIn, pfOut);

fclose(pfIn);
fclose(pfOut);
}
int main()
{
text();
system("pause");
return 0;
}
CommentConvert.c文件

#include "CommentConvert.h"
#include <assert.h>

enum STATE state = NUL_STATE;

void DoConvertWork(FILE *pfIn, FILE *pfOut)
{
while (state != END_STATE)
{
switch (state)
{
case NUL_STATE:
DoNulState(pfIn, pfOut);
break;
case C_STATE:
DoCState(pfIn, pfOut);
break;
case CPP_STATE:
DoCppState(pfIn, pfOut);
break;
default:
break;
}
}
}

void DoNulState(FILE *pfIn, FILE *pfOut)
{
assert(pfIn);
assert(pfOut);

int first = fgetc(pfIn);
switch (first)
{
case '/':
{
int second = fgetc(pfIn);
if (second == '*') //如果第二个字符为'*',则为C语言注释
{
state = C_STATE;
fputc(first, pfOut);
fputc('/', pfOut);
}
else if (second == '/') //如果第二个字符为'/',则为CPP注释
{
state = CPP_STATE;
fputc(first, pfOut);
fputc(second, pfOut);
}
break;
}
case EOF:
state = END_STATE;
break;
default:
fputc(first, pfOut);
break;
}
}

void DoCState(FILE *pfIn, FILE *pfOut) //C语言注释转换
{
assert(pfIn);
assert(pfOut);

int first = fgetc(pfIn);
switch (first)
{
case '*':
{
int second = fgetc(pfIn);
if (second == '/')
{
int third = fgetc(pfIn);
switch (third)
{
case '\n':
fputc(third, pfOut); // 返回开始处继续寻找注释
state = NUL_STATE;
break;
case '/': // 判断是否为连续C语言注释
fputc('\n', pfOut);
ungetc(third, pfIn);
state = NUL_STATE;
break;
case EOF:
state = END_STATE;
break;
default:
fputc('\n', pfOut);
fputc(third, pfOut);
state = NUL_STATE;
break;
}
}
else if (second == '*') //处理注释行中多余*
{
fputc(second, pfOut);
ungetc(second, pfIn);
state = C_STATE;
}
else
{
fputc(first, pfOut);
fputc(second, pfOut);
state = C_STATE;
}
}
break;
case '\n': //判断多行注释
fputc(first, pfOut);
fputc('/' , pfOut);
fputc('/', pfOut);
break;
default:
fputc(first, pfOut);
break;
}
}

void DoCppState(FILE *pfIn, FILE *pfOut)
{
assert(pfIn);
assert(pfOut);

int first = fgetc(pfIn);
switch (first)
{
case '\n':
fputc(first, pfOut);
state = NUL_STATE;
break;
case EOF:
state = END_STATE;
break;
default:
fputc(first, pfOut);
break;
}
}