重庆分公司,新征程启航
为企业提供网站建设、域名注册、服务器等服务
将C语言注释转换成C++注释
创新互联建站自2013年创立以来,先为通州等服务建站,通州等地企业,进行企业商务咨询服务。为通州企业网站制作PC+手机+微官网三网同步一站式服务解决您的所有建站问题。
#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#include #include #include #include"AnnotationConvert.h" int main() { test(); system("pause"); return 0; }
运行结果: