本博客主要考虑以下几种情况,可能有的地方没有考虑到,望读者指出。
// 1.一般情况
/* int i = 0; */
// 2.换行问题
/* int i = 0; */int j = 0;
/* int i = 0; */
int j = 0;
// 3.匹配问题
/*int i = 0;/*xxxxx*/
// 4.多行注释问题
/*
int i=0;
int j = 0;
int k = 0;
*/int k = 0;
// 5.连续注释问题
/**//**/
// 6.连续的**/问题
/***/
// 7.C++注释问题
// /*xxxxxxxxxxxx*/
以下为主要代码:
主函数:
#define _CRT_SECURE_NO_WARNINGS 1 #include <stdio.h> #include <stdlib.h> #include "AnnotationConver.h" int main() { AnnotationConver("input.c", "output.c"); system("pause"); return 0; }
AnnotationConver.h:
#pragma once typedef enum State { C_BEGIN, C_END, }State; void AnnotationConver(const char *inputFile, const char *outputFile);
AnnotationConver.c:
#define _CRT_SECURE_NO_WARNINGS 1 #include <stdio.h> #include <stdlib.h> #include <assert.h> #include "AnnotationConver.h" static void Convert(FILE *fIn, FILE *fOut) { assert(fIn); assert(fOut); char first = 0; char second = 0; State tag = C_END; do { first = fgetc(fIn); switch (first) { case '/': second = fgetc(fIn); if (second == '*') { if (tag == C_END) { fputc('/', fOut); fputc('/', fOut); tag = C_BEGIN; } else { fputc(first, fOut); fputc(second, fOut); } } else if (second == '/') { fputc('/', fOut); fputc('/', fOut); char next = fgetc(fIn); while (next != '\n'&& next != EOF) { fputc(next, fOut); next = fgetc(fIn); } if (next == '\n') { fputc(next, fOut); } } else { fputc(first, fOut); fputc(second, fOut); } break; case '\n': if (tag == C_BEGIN) { fputc(first, fOut); fputc('/', fOut); fputc('/', fOut); } else { fputc(first, fOut); } break; case '*': second = fgetc(fIn); if (second == '/') { //换行问题 char next = fgetc(fIn); /*连续注释*/ if (next == '/') { fseek(fIn, -1, SEEK_CUR); } /*换行问题*/ else { if (next != '\n'&& next != EOF) { fputc('\n', fOut); } if (next != EOF) { fputc(next, fOut); } } tag = C_END; } /*连续的**问题*/ else if (second == '*') { fputc(second, 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); } void AnnotationConver(const char *inputFile, const char *outputFile) { assert(inputFile); assert(outputFile); FILE *fIn = fopen(inputFile,"r"); if (fIn == NULL) { printf("打开文件%s失败! errno: %d\n", inputFile, errno); return; } FILE *fOut = fopen(outputFile, "w"); if (fOut == NULL) { fclose(fIn); printf("打开文件%s失败! errno: %d\n", outputFile, errno); return; } Convert(fIn, fOut); fclose(fIn); fclose(fOut); }