将C语言注释转换成C++注释
#pragma once #pragma warning (disable:4996) typedef enum ConvertState { SUCCESS,//转换成功 FILE_ERROR,//打开文件失败 NO_MATCH,//转换失败 } ConvertState; //转换的状态 typedef enum State { C_BEGIN,//C语言注释开始 C_END,//C语言注释结束 CPP_BEGIN,//C++注释开始 CPP_END,//C++注释结束 }State; ConvertState Convert(FILE *fin, FILE *fout) { ConvertState ret = SUCCESS; char first, second; State tag = C_END; assert(fin); assert(fout); do{ first = fgetc(fin); switch (first) { case '/': second = fgetc(fin); if (second == '*') { //3/匹配问题 if (tag == C_END) { fputc('/',fout); fputc('/',fout); tag = C_BEGIN; } else { fputc('/', fout); fputc('*', fout); } } else if (second == '/') { char next; fputc('/', fout); fputc('/', fout); do{ next = fgetc(fin); fputc(next, fout); if (next == EOF) return ret; } while (next != '\n'); } else { fputc(first, fout); fputc(second, fout); } break; case '\n': //4.多行注释问题 fputc('\n', fout); if (tag == C_BEGIN) { fputc('/', fout); fputc('/', fout); } break; case '*': second = fgetc(fin); if (second == '/') { //2.换行问题 char next = fgetc(fin); //5.连续注释问题 if (next == '/') { fputc('/n', fout); fseek(fin, -1, SEEK_CUR); } else if (next != '\n'&&next != EOF) { fputc('\n', fout); fputc(next, fout); } else { fputc('/n', fout); } tag = C_END; } else if (second == '*') { fputc(first, fout); fseek(fin, -1, SEEK_CUR); } else { fputc(first, fout); fputc(second, fout); } break; default: if (first != EOF) { fputc(first, fout); } break; } } while (first != EOF); if (tag != C_END) { ret = NO_MATCH; } return ret; } ConvertState AnnotationConvert(const char*inputfile, const char* outputfile) { ConvertState ret; FILE* fout, *fin; fin = fopen(inputfile, "r"); if (fin == NULL) { printf("打开文件%s失败,errno:%d\n", inputfile, errno); return FILE_ERROR; } fout = fopen(outputfile, "w"); if (fout == NULL) { fclose(fin); printf("打开文件%s失败,errno:%d\n", outputfile, errno); return FILE_ERROR; } ret = Convert(fin, fout); fclose(fin); fclose(fout); return ret; }; void test() { char *inputfile = "C"; char *outputfile = "C++"; ConvertState flag=AnnotationConvert(inputfile, outputfile); if (flag == SUCCESS) { printf("转换成功,请查看"); } else if (flag == FILE_ERROR) { printf("打开文件失败"); } else { printf("转换失败=_=||"); } } #define _CRT_SECURE_NO_WARNINGS 1 #include<stdio.h> #include<stdlib.h> #include<assert.h> #include<errno.h> #include"AnnotationConvert.h" int main() { test(); system("pause"); return 0; }
运行结果:
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。