IO注释转换---CPP风格

来源:互联网 发布:听书神器软件 编辑:程序博客网 时间:2024/06/01 10:09
头文件 convert.h#ifndef __CONVERT_H_#define __CONVERT_H_#define _CRT_SECURE_NO_WARNINGS 1#include <stdio.h>#include <windows.h>#endif //__CONVERT_H_enum{ CSTATUS, CPPSTATUS, NULLSTATUS,EOFSTATUS };#define INPUT "input.txt"#define OUTPUT "output.txt"void convert_work();void do_CPP(FILE*opt, FILE*ipt);void do_C(FILE*opt, FILE*ipt);void do_NULL(FILE*opt, FILE*ipt);测试 test.c#include "convert.h"int main(){convert_work();system("pause");return 0;}实现 convert.c#include  "convert.h"int status = NULLSTATUS;  //定义全局状态变量void do_NULL(FILE*opt, FILE*ipt)  //空状态{int s = fgetc(opt);  //在opt中读入一个字符switch (s){case '/':{int f = fgetc(opt);switch (f){case'/':fputc('/', ipt);  //如果遇到//将输出并进入CPP状态fputc('/', ipt);status = CPPSTATUS;break;case'*':fputc('/', ipt);  //遇到/*发生注释转换//进入C状态fputc('/', ipt);status = CSTATUS; break;case EOF:status = EOFSTATUS; break;//遇到EOF进入EOF状态default:fputc('/', ipt);//遇到a/b类似的情况,先输出/{if (f != '\n')//若/后面不为\n,输出\后的内容fputc(f, ipt);else         //若为\n直接换行fputc('\n', ipt);}; break;}}break;case EOF:status = EOFSTATUS; break;default:fputc(s, ipt); break;  //以上均不满足直接写入ipt}}void do_C(FILE*opt, FILE*ipt)  //C状态{int c = fgetc(opt);switch (c){case'*':{int s = fgetc(opt);switch (s){case '/':      //若为*/{int a = fgetc(opt);  //再获取一个字符判断是否为\nif (a != '\n')    //不为\n后面仍有内容{fputc('\n', ipt);   //换行.退回获取的字符ungetc(a, opt);}elsefputc('\n',ipt);  //*/后为\n直接换行status = NULLSTATUS;  //遇到*/之后的内容不是C状态}; break;   case EOF:status = EOFSTATUS; break;   default:fputc('*', ipt); ungetc(s, opt); status = CSTATUS; break;}}break;case'\n':fputc('\n', ipt); fputc('/', ipt); fputc('/', ipt); status = CSTATUS; break;  //在C注释中遇到换行,换行并加//注释case EOF:status = EOFSTATUS; break;default:fputc(c, ipt); status = CSTATUS; break;  //没有遇到*/均在C状态}}void do_CPP(FILE*opt, FILE*ipt)  //C++状态{int s = fgetc(opt);switch (s){case '\n':fputc('\n', ipt); status = NULLSTATUS; break;   //换行即结束注释case EOF:status = EOFSTATUS; break;default:fputc(s, ipt);  break;}}void convert(FILE* opt, FILE * ipt){while (status != EOFSTATUS){switch (status)   //4种状态{case NULLSTATUS:do_NULL(opt, ipt);break;case CSTATUS:do_C(opt, ipt);break;case CPPSTATUS:do_CPP(opt, ipt);break;case EOFSTATUS:   //EOF状态直接退出break;default:  break;}}}void convert_work(){FILE* opt = fopen(INPUT, "r");   //以读方式打开FILE* ipt = fopen(OUTPUT, "w");  //以写方式打开if (opt == NULL||ipt==NULL){printf("fopen error!\n");}convert(opt, ipt);fclose(opt);opt = NULL;fclose(ipt);ipt = NULL;}

看一下程序运行结果:


原创粉丝点击