这是头文件:
CommentConvert.h
#ifndef __Comment_Convet_H__
#define __Comment_Convet_H__
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
typedef enum CONVERT_STATE
{
NULL_STATE,
C_STATE,
CPP_STATE,
END_STATE,
}StateType;
#define INPUTFILENAME "input.c"
#define OUTPUTFILENAME "output.c"
void CommentConvert();
void ConvertWork(FILE *read, FILE *write);
void Handle_NULL_STATE(FILE *read, FILE *write);
void Handle_C_STATE(FILE *read, FILE *write);
void Handle_CPP_STATE(FILE *read, FILE *write);
void Handle_END_STATE(FILE *read, FILE *write);
#endif __Comment_Convet_H__
CommentConvert.c
#include "CommentConvert.h"
StateType state;
void Handle_NULL_STATE(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:
state = END_STATE;
break;
default:
fputc(first, write);
break;
}
}
void Handle_C_STATE(FILE *read, FILE *write)
{
int first = fgetc(read);
int second = 0;
int third = 0;
switch (first)
{
case '*':
second = fgetc(read);
if (second == '/')// 舍弃“*/”
{
third = fgetc(read);
if (third != '\n')
{
fputc('\n', write);
state = NULL_STATE;
ungetc(third, read);
}
else
{
ungetc(third, read);
state = NULL_STATE;
}
}
else
{
fputc(first, write);
ungetc(second, read);
}
break;
case '\n':
fputc(first, write);
fputc('/', write);
fputc('/', write);
break;
case EOF:
state = END_STATE;
break;
default:
fputc(first, write);
break;
}
}
void Handle_CPP_STATE(FILE *read, FILE *write)
{
int first = fgetc(read);
switch (first)
{
case'\n':
fputc('\n', write);
state = NULL_STATE;
break;
case EOF:
fputc(first, write);
state = END_STATE;
break;
default:
fputc(first, write);
break;
}
}
void Handle_END_STATE(FILE *read, FILE *write)
{
;
}
void ConvertWork(FILE *read, FILE *write)
{
state = NULL_STATE;
while (state != END_STATE)
{
switch (state)
{
case NULL_STATE:
Handle_NULL_STATE(read, write);
break;
case C_STATE:
Handle_C_STATE(read, write);
break;
case CPP_STATE:
Handle_CPP_STATE(read, write);
break;
default:
break;
}
}
}
void CommentConvert()
{
FILE* pWrite = NULL;
FILE* pRead = fopen(INPUTFILENAME, "r");
if (pRead == NULL)
{
perror("open file to read");
exit(EXIT_FAILURE);
}
pWrite = fopen(OUTPUTFILENAME, "w");
if (pWrite == NULL)
{
perror("open file to write");
exit(EXIT_FAILURE);
}
ConvertWork(pRead,pWrite);
fclose(pRead);
fclose(pWrite);
}
下面是测试部分:
test.c
#include "CommentConvert.h"
int main()
{
CommentConvert();
system("pause");
return 0;
}
程序运行需要在目录下读取一个文件“input.c”
手动创建这个文件,并写入相应内容即可;
程序运行结束后,产生一个“output.c”的文件,将input.c中的c语言注释修改为c++注释。
关于项目的详细解析及其主要思路,请继续关注我的博客。