pace 10 (注释转换)

来源:互联网 发布:房产中介端口推荐 编辑:程序博客网 时间:2024/06/01 23:04

代码功能:将C注释转换为C++注释

有普通、C、CPP、结束四种状态,各状态转换条件如下


//convert.h#pragma once#define INPUT "input.c"#define OUTPUT "output.c"enum STA{NULSTAT,CSTAT,CPPSTAT,EOFSTAT,}STATUS;//定义枚举类型,表示四种状态


//convert.c#include <stdio.h>#include "convert.h"enum STA STATUS = NULSTAT;    //将代码状态预制为普通状态void Test_NULSTAT(FILE *ipf, FILE *opf){int c = fgetc(ipf);switch ( c ){case '/':                                  //若读取为 / ,则有可能是   C   C++   A / B    /EOF{int s = fgetc(ipf);switch ( s ){case '*':                          // Cfputc('/',opf);fputc('/', opf);           // 输出  //STATUS = CSTAT;            // 状态置位 Cbreak;case '/':                          // C++fputc('/', opf);fputc('/', opf);           // 输出  // STATUS = CPPSTAT;          // 状态置位  C++break;case EOF:                          // 结束fputc(c, opf);STATUS = EOFSTAT;          // 状态置位   EOFbreak;default:fputc(c, opf);break;}}break;case EOF:fputc(c, opf);STATUS = EOFSTAT;break;default:fputc(c, opf);STATUS = NULSTAT;break;}}void Test_CSTAT(FILE *ipf, FILE *opf){int c = fgetc(ipf);switch ( c ){case '\n':fputc(c, opf);fputc('/', opf);fputc('/', opf);STATUS = CSTAT;break;case '*':{int s = fgetc(ipf);switch ( s ){case '/':fputc('\n', opf);STATUS = NULSTAT;break;case EOF:fputc('/', opf);STATUS = EOFSTAT;break;default:ungetc(c,ipf);           //例如碰到 **/ 的情况,应退回刚读取的数据,避免将 **看为一组 意外丢掉注释结束符fputc(c, opf);STATUS = CSTAT;break;}}break;case EOF:fputc(c, opf);STATUS = EOFSTAT;break;default:fputc(c, opf);STATUS = CSTAT;break;}}void Test_CPPSTAT(FILE *ipf, FILE *opf){int c = getc(ipf);switch ( c ){case EOF:fputc(c, opf);STATUS = EOFSTAT;break;case '\n':fputc(c, opf);STATUS = NULSTAT;break;default:fputc(c, opf);STATUS = CPPSTAT;break;}}void Test_EOFSTAT(FILE *ipf, FILE *opf){int c = getc(ipf);fputc(c, opf);STATUS = EOFSTAT;}void Test_Convert_Main(FILE *ipf, FILE *opf){while (STATUS != EOFSTAT)     //只要文件没结束一直进行判断和转换{switch (STATUS){case NULSTAT:Test_NULSTAT(ipf, opf);break;case CSTAT:Test_CSTAT(ipf, opf);break;case CPPSTAT:Test_CPPSTAT(ipf, opf);break;case EOFSTAT:Test_EOFSTAT(ipf, opf);break;default:break;}}}


//test.c#define _CRT_SECURE_NO_WARNINGS 1#include <stdio.h>#include <stdlib.h>#include <Windows.h>#include "convert.h"int main(){FILE *IP = fopen(INPUT, "r");FILE *OP = fopen(OUTPUT, "w");if (IP == NULL || OP == NULL){perror("Error opening file");exit(1);}Test_Convert_Main(IP,OP);fclose(IP);fclose(OP);system("pause");return 0;}


演示结果

input.c


output.c


原创粉丝点击