將 / * … * / 註釋轉換爲 / / 註釋。
transform.h
#ifndef __transform_h__
#define __transform_h__
#define MY_INPUT "input.c"
#define MY_OUTPUT "output.c"
void comment_transform_main();
enum STATUS{ NORSTATUS, CSTATUS, CPPSTATUS, EOFSTATUS };
#endif //__transform_h__
transform.c
#include <stdio.h>
#include<assert.h>
#include"transform.h"
enum STATUS status = NORSTATUS;
//處理正常狀態字符
void tra_nor(FILE *ifp, FILE *ofp)
{
char fc = fgetc(ifp);
switch (fc)
{
case '/':
{
fputc('/', ofp);
char sc = fgetc(ifp);
switch (sc)
{
case '/':
fputc('/', ofp);
status = CPPSTATUS;
break;
case '*':
fputc('/', ofp);
status = CSTATUS;
break;
case EOF:
status = EOFSTATUS;
default:
fputc(sc,ofp);
status = NORSTATUS;
break;
}
}
break;
case EOF:
fputc(fc,ofp);
status = EOFSTATUS;
break;
default:
fputc(fc, ofp);
status = NORSTATUS;
break;
}
}
//處理c風格註釋中的字符
void tra_c(FILE *ifp, FILE *ofp)
{
char fc = fgetc(ifp);
switch (fc)
{
case '*':
{
char sc = fgetc(ifp);
switch (sc)
{
case '/':
fputc('\n', ofp);
status = NORSTATUS;
break;
case EOF:
status = EOFSTATUS;
break;
default:
fputc(fc,ofp);
fputc(sc, ofp);
status = CSTATUS;
break;
}
}
break;
case '\n':
fputc(fc, ofp);
fputc('/', ofp);
fputc('/', ofp);
status = CSTATUS;
break;
case EOF:
fputc(fc, ofp);
status = EOFSTATUS;
break;
default:
fputc(fc, ofp);
status = CSTATUS;
break;
}
}
//處理c++風格註釋中的字符
void tra_cpp(FILE *ifp, FILE *ofp)
{
char fc = fgetc(ifp);
switch (fc)
{
case '\n':
fputc(fc, ofp);
status = NORSTATUS;
break;
case EOF:
fputc(fc, ofp);
status = EOFSTATUS;
break;
default:
fputc(fc, ofp);
status = CPPSTATUS;
break;
}
}
//處理EOF
void tra_eof(FILE *ifp, FILE *ofp)
{
return;
}
//轉換函數
void transform(FILE *ifp,FILE *ofp)
{
while (status != EOFSTATUS)
{
switch (status)
{
case NORSTATUS:
tra_nor(ifp, ofp);
break;
case CSTATUS:
tra_c(ifp, ofp);
break;
case CPPSTATUS:
tra_cpp(ifp, ofp);
break;
case EOFSTATUS:
tra_eof(ifp, ofp);
break;
default:
break;
}
}
}
//註釋轉換函數
void comment_transform_main()
{
FILE * ifp = fopen(MY_INPUT,"r");
FILE * ofp = fopen(MY_OUTPUT, "w");
assert(ifp);
assert(ofp);
transform(ifp, ofp);
fclose(ifp);
fclose(ofp);
}
test.c
#include <stdio.h>
#include"transform.h"
#include<windows.h>
int main()
{
comment_transform_main();
printf("Complete transformation!\n\n");
system("pause");
return 0;
}