AnnotationConversion.h
# pragma once #define _CRT_SECURE_NO_WARNINGS 1 #include <stdio.h> #include <assert.h> #include <errno.h> typedef enum State { c_BEGIN, c_END }State; typedef enum RunState { SUCCESS, FILE_WRONG, NO_MATCH }RunState; RunState AnnotationConvert(const char* input,const char* output);
AnnotationConversion.c
#include "AnnotationConversion.h" RunState convert(FILE* input, FILE* output) { char first,second; RunState ret = SUCCESS; State tag = c_END; assert(input); assert(output); do{ first = fgetc(input); switch(first) { case '/': second = fgetc(input); if(second == '*') { //3.匹配问题 if(tag == c_END) { fputc('/',output); fputc('/',output); tag = c_BEGIN; } else { fputc('/', output); fputc('*', output); } } else if(second == '/')//C++注释问题 { char next; fputc(first, output); fputc(second, output); do { next = fgetc(input); fputc(next, output); if(next == EOF) { return ret; } }while(next != '\n'); } else { fputc(first, output); fputc(second, output); } break; case '\n'://4.多行注释问题 if(tag == c_BEGIN) { fputc(first, output); fputc('/', output); fputc('/', output); } else { fputc(first, output); } break; case '*': second = fgetc(input); if(second == '/') { //2.换行情况 char next = fgetc(input); if(next == '/')//5.连续注释问题 { fputc('\n', output); fseek(input, -1, SEEK_CUR); } else if(next != '\n'&& next != EOF) { fputc('\n', output); fputc(next, output); } else { fputc('\n', output); } tag = c_END; } else if(second == '*')//6.连续的***/问题 { fputc(first, output); fseek(input, -1, SEEK_CUR); } else { fputc(first,output); fputc(second,output); } break; default: if(first != EOF) { fputc(first,output); } break; } }while(first != EOF); if(tag == c_BEGIN) { return NO_MATCH; } } RunState AnnotationConvert(const char* inputFile,const char* outputFile) { FILE* fIn,*fOut; RunState ret; fIn = fopen(inputFile, "r"); if(fIn == NULL) { printf("%s文件打开失败 Error:%d\n",inputFile,errno); return FILE_WRONG; } fOut = fopen(outputFile, "w"); if(fOut == NULL) { fclose(fIn); printf("%s文件打开失败 Error:%d\n",outputFile,errno); return FILE_WRONG; } ret = convert(fIn,fOut); fclose(fIn); fclose(fOut); return ret; }
Test.c
#include <stdlib.h> #include "AnnotationConversion.h" int main() { RunState ret; ret = AnnotationConvert("inputFile.c"," outputFile.c"); if(ret ==SUCCESS) { printf("SUCCESS"); } else if(ret == FILE_WRONG) { printf("FILE_WRONG"); } else { printf("NO_MATCH"); } system("pause"); return 0; }
inputFile.c
1.一般情况 /*int m = 0;*/ 2.换行问题 /*int i = 0;*/int j = 0; /*int i = 0;*/ int j = 0; 3.匹配问题 /*int i = 0/*j = 0*/ 4.多行注释问题 /* int i = 0; int j = 1; */int k = 2; 5.连续注释问题 /*aaa*//*bbb*/ 6.连续的***/问题 /***/ 7.c++注释问题 // /*int i = 0;
outputFile.c
1.一般情况 //int m = 0; 2.换行问题 //int i = 0; int j = 0; //int i = 0; int j = 0; 3.匹配问题 //int i = 0/*j = 0 4.多行注释问题 // //int i = 0; //int j = 1; // int k = 2; 5.连续注释问题 //aaa //bbb 6.连续的** 问题 //* 7.c++注释问题 // /*int i = 0;