本博客主要考慮如下幾種狀況,可能有的地方沒有考慮到,望讀者指出。ide
// 1.通常狀況函數
/* int i = 0; */spa
// 2.換行問題get
/* int i = 0; */int j = 0;input
/* int i = 0; */博客
int j = 0;it
// 3.匹配問題io
/*int i = 0;/*xxxxx*/class
// 4.多行註釋問題next
/*
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); }