在此次小项目中的不足之处:在编程过程中由于对extern运用不熟悉,导致文件链接错误,除此之外粗心之下变量名写错,造成死循环。
头文件(turns.h):
#ifndef _TURNS_H_
#define _TURNS_H_
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#define INPUTFILE "input.c"
#define OUTPUTFILE "output.c"
enum{
ORDS,
CS,
CPPS,
EOFS,
};
void turns();
#endif //_TURNS_H_
主函数文件(main-body.c):
#include "turns.h"
int main()
{
turns();
system("pause");
return 0;
}#include "turns.h"
int main()
{
turns();
system("pause");
return 0;
}
转换函数文件(turns.c):
#include "turns.h"
extern int stu = 0;
void C_Stu(FILE * ifp, FILE * ofp) //c注释部分处理
{
int c1 = 0;
int c2 = 0;
int c3 = 0;
while (1)
{
c1 = fgetc(ifp);
switch (c1)
{
case '/':
{
c2 = fgetc(ifp);
fputc(c1, ofp);
if (c2 == '*')
{
fputc('/', ofp);
}
else if (c2 == '/')
{
stu = CPPS;
}
else if (c2 == EOF)
{
stu = EOFS;
}
break;
}
case '\n':
{
fputc(c1, ofp);
fputc('/', ofp);
fputc('/', ofp);
break;
}
case '*':
{
c2 = fgetc(ifp);
c3 = fgetc(ifp);
if (c2 == '/')
{
if (c3 != '\n')
fputc('\n', ofp);
stu = ORDS;
}
ungetc(c3, ifp);
break;
}
default:
fputc(c1, ofp);
break;
}
if (stu == EOFS || stu == ORDS || stu == CPPS)
break;
}
}
void Cpp_Stu(FILE * ifp, FILE * ofp) //c++注释部分处理
{
int c = 0;
while (1)
{
c = fgetc(ifp);
if (c == '\n')
{
fputc(c, ofp);
stu = ORDS;
break;
}
if (c == EOF)
{
stu = EOFS;
break;
}
fputc(c, ofp);
}
}
void Ord_Stu(FILE * ifp, FILE * ofp) //非注释部分处理
{
int c1 = 0;
int c2 = 0;
while (1)
{
c1 = fgetc(ifp);
if (c1 == '/')
{
c2 = fgetc(ifp);
switch (c2)
{
case '*':
stu = CS;
break;
case '/':
stu = CPPS;
break;
default:
break;
}
ungetc(c2, ifp);
ungetc(c1, ifp);
break;
}
if (c1 == EOF)
{
stu = EOFS;
break;
}
fputc(c1, ofp);
}
}
static void turns_work(FILE * ifp, FILE * ofp)
{
while (stu != EOFS)
{
switch (stu)
{
case ORDS:
Ord_Stu(ifp, ofp);
break;
case CS:
C_Stu(ifp, ofp);
break;
case CPPS:
Cpp_Stu(ifp, ofp);
break;
case EOFS:
break;
default:
break;
}
}
}
void turns()
{
FILE * ifp = fopen(INPUTFILE, "r");
FILE * ofp = fopen(OUTPUTFILE, "w");
if (ifp == NULL || ofp == NULL)
{
perror("error!");
}
turns_work(ifp, ofp);
fclose(ifp);
fclose(ofp);
}