C语言注释行转换

来源:互联网 发布:linux结束所有进程命令 编辑:程序博客网 时间:2024/05/28 05:15
头文件
#ifndef __CONVERT_H__#define __CONVERT_H__enum{NULSTAT,CSTAT,CPPSTAT,EOFSTAT,};

函数实现部分

#define INPUT"input.c"#define OUTPUT"output.c"void convert_main();#endif#define _CRT_SECURE_NO_EARNINGS 1#include<stdio.h>#include"convert.h"static int status = NULSTAT;void do_nul_start(FILE*ipf, FILE*opf){int c = fgetc(ipf);switch (c){case '/':{ int s = fgetc(ipf); switch (s) { case '*': fputc('/', opf); fputc('/', opf); status = CSTAT; break;case '/': fputc('/', opf); fputc('/', opf); status = CPPSTAT; break;        default://a/b       fputc('/',opf);      ungetc(s,ipf);//将字符退回到输入文件,检查下一个      status = NULSTAT;       break; }     }break;case EOF:status = EOFSTAT;break;default:fgetc(c, opf);//将字符写入输入文件break;}}void do_cpp_start(FILE*ipf, FILE*opf){int c = fgetc(ipf);switch (c){case '\n':fputc(c,opf);status = EOFSTAT;break;default:fputc(c, opf);status = CPPSTAT;break;}}void do_c_start(FILE*ipf, FILE*opf){int c = fgetc(ipf);switch (c){case '\n':fputc("\n", opf);fputc('/', opf);fputc('/', opf);status = CSTAT;break;case '*':{int s = fgetc(ipf);switch (s){case '/':{ int n = fgetc(ipf); if (n == '\n') fputc('\n', opf); else{ fputc('\n', opf); ungetc(n, opf); }}status = NULSTAT;break;case EOF:status = EOFSTAT;default:ungetc(s, ipf);//无法知道下一个是什么字符,所以退回去处理比如**/status = CSTAT;break;}}break;case EOF:status = EOFSTAT;fputc(c,opf);break;}}static void convert_work(FILE*ipf, FILE*opf){while (status != EOFSTAT){switch (status){case NULSTAT:do_null_start(ipf, opf);break;case CPPSTAT:do_cpp_start(ipf, opf);break;case CSTAT:do_c_start(ipf, opf);break;case EOFSTAT:do_eof_start(ipf, opf);break;default:break;}}}void convert_main(){FILE *ipf = fopen(INPUT, "r");FILE *opf = fopen(OUTPUT, "w");if (ipf == NULL || opf == NULL){fprintf(stderr,"open file error\n");exit(1);}convert_work(ipf, opf);fclose(ipf);fclose(opf);}


测试部分

#define _CRT_SECURE_NO_WARNINGS 1#include"convert.h"int main(void){convert_main();system("pause");}


原创粉丝点击