convert.h
#ifndef _CONVERT_COMMENT_H_
#define _CONVER_COMMENT_H_
#include <stdio.h>
#include <windows.h>
#define INPUTFILE "input.c"//输入
#define OUTPUTFILE "output.c"//输出
enum { CSTATUS, CPPSTATUS, NULLSTATUS, EOFSTATUS };
void connver_main();
void connver_work(FILE *ifp, FILE* ofp);
void do_null_status(FILE *ifp, FILE *ofp);
void do_c_status(FILE *ifp, FILE *ofp);
void do_cpp_status(FILE *ifp, FILE *ofp);
#endif
convert.c
#include "convert.h"
#pragma warning(disable:4996)
int status = NULLSTATUS;
void do_null_status(FILE *ifp, FILE *ofp)
{
int c = fgetc(ifp);
switch (c)
{
case '/':
{
int s = fgetc(ifp);
switch (s)
{
case '*':
fputc('/', ofp);
fputc('/', ofp);
status = CSTATUS;
break;
case '/':
fputc('/', ofp);
fputc('/', ofp);
status = CPPSTATUS;
break;
case EOF:
fputc('/', ofp);
status = EOFSTATUS;
break;
default:
fputc('/', ofp);
ungetc(s, ifp);//回退
break;
}
}
break;
case '\n':
fputc(c, ofp);
break;
case EOF:
status = EOFSTATUS;
break;
default:
fputc(c, ofp);
break;
}
}
void do_c_status(FILE *ifp, FILE *ofp)
{
int c = fgetc(ifp);
switch (c)
{
case '*':
{
int s = fgetc(ifp);
switch (s)
{
case '/': //遇到C注释结尾,结尾的 */ 不写入。
fputc('\n', ofp);
status = NULLSTATUS;
break;
case '\n':
fputc('\n', ofp);
fputc('/', ofp);
fputc('/', ofp);
break;
default:
fputc(c, ofp); //可能遇到的是乘法运算
ungetc(s, ifp); //第二个读取的字符退回去
status = CSTATUS;
break;
}
break;
}
case '\n':
fputc(c, ofp);
fputc('/', ofp);
fputc('/', ofp);
//status = CPPSTATUS;(错误,无法实现)
break;
case EOF:
status = EOFSTATUS;
break;
default:
fputc(c, ofp);
status = CSTATUS;
break;
}
}
void do_cpp_status(FILE *ifp, FILE *ofp)
{
int c = fgetc(ifp);
switch (c)
{
case '\n': //C++注释遇到换行结束
fputc(c, ofp);
status = NULLSTATUS;
break;
case EOF:
status = EOFSTATUS;
break;
default:
fputc(c, ofp);
status = CPPSTATUS;
break;
}
}
void do_eof_status(FILE *ifp, FILE *ofp)
{
return;
}
static void connver_work(FILE *ifp, FILE* ofp)
{
while (status != EOFSTATUS)
{
switch (status)
{
case NULLSTATUS:
do_null_status(ifp, ofp);
break;
case CSTATUS:
do_c_status(ifp, ofp);
break;
case CPPSTATUS:
do_cpp_status(ifp, ofp);
break;
case EOFSTATUS:
break;
default:
break;
}
}
}
void connver_main()
{
FILE *ifp = fopen("ITPUTFILE.txt", "r");
FILE *ofp = fopen("OUTPUTFILE.txt", "w");
if (ifp == NULL || ofp == NULL)
{
perror("fopen");
//fprintf(stderr, " open file error\n");
return;
}
connver_work(ifp, ofp);
fclose(ifp);
fclose(ofp);
}
main.c
#include "convert.h"
int main()
{
connver_main();
//XP:极限编程
system("pause");
return 0;
}