#include<stdio.h> typedef enum Tag { C_ANNOTAION_START = 0, // C注釋的開始 C_ANNOTAION_END = 1, // C注釋的結束 }Tag; typedef enum State { SUCCESS = 1,//成功 OPEN_FILE_ERROR,//打開文件失敗 NO_MATCH,//文檔不匹配 OTHER,//其他 }State; State AnnotationConvert(FILE* cIn,FILE* cOut ) { char FirstCh, SecondCh; Tag Is_Start = C_ANNOTAION_END;//是否開始轉換 do { FirstCh = fgetc(cIn); switch (FirstCh) { // 1.一般情況 ///* int i = 0; */ case '/': SecondCh = fgetc(cIn); // 3.匹配問題 ///*int i = 0;/*xxxxx*/ if (SecondCh == '*'&&Is_Start == C_ANNOTAION_END) { fputc('/', cOut); fputc('/', cOut); Is_Start = C_ANNOTAION_START; } else if (SecondCh == '/')//c++注釋問題 { char Next = fgetc(cIn); fputc('/', cOut); fputc('/', cOut); while (Next != '\n'&&Next!=EOF) { fputc(Next, cOut); Next = fgetc(cIn); } //FirstCh = Next; fseek(cIn, -1, SEEK_CUR); } else { fputc(FirstCh, cOut); fputc(SecondCh, cOut); } break; case '*': SecondCh = fgetc(cIn); // 2.換行問題/5.連續注釋問題 ///* int i = 0; */int j = 0; ///* int i = 0; */ if (SecondCh == '/') { char Next = 0; Next = fgetc(cIn); if (Next != '\n'&&Next != EOF) { fseek(cIn, -1, SEEK_CUR); fputc('\n', cOut); } else { fputc('\n', cOut); } Is_Start = C_ANNOTAION_END; } else if (SecondCh == '*') { fputc(FirstCh,cOut); fseek(cIn, -1, SEEK_CUR); break; } else { fputc(FirstCh, cOut); fputc(SecondCh, cOut); } break; // 4.多行注釋問題 case '\n': fputc('\n', cOut); if (Is_Start == C_ANNOTAION_START) { fputc('/', cOut); fputc('/', cOut); } break; default: fputc(FirstCh, cOut); break; } } while (FirstCh != EOF); if (Is_Start == C_ANNOTAION_START) { return NO_MATCH; } return SUCCESS; } State StartAnnotationConvert(const char * input, const char * output) { FILE* cIn = fopen(input, "r"); FILE* cOut = fopen(output, "w"); State ret = 0; if (cIn == NULL) { fclose(cOut); return OPEN_FILE_ERROR; } if (cOut == NULL) { fclose(cIn); return OPEN_FILE_ERROR; } ret=AnnotationConvert(cIn, cOut); fclose(cIn); fclose(cOut); return ret; } int main() { State ret = StartAnnotationConvert("input.c", "output.c"); if (ret == SUCCESS) { printf("轉換成功!\n"); } else if (ret ==NO_MATCH) { printf("文檔未找到匹配結尾\n"); } else if (ret == OPEN_FILE_ERROR) { printf("打開文件失敗\n"); } return 0; }