题目描述:
1. 将一个.c文件1复制到另一个文件2中,要求过滤掉文件1中的注释。
注释类型:以//开头或者/**/中的注释。用一个函数完成该功能。
基本要求:假设//或者/**/不会出现在printf语句中。
高级要求:要能处理printf中的//或者/**/
练习目的:练习文件的基本操作
//klkl//kk;;l/*l;;l*/
/*klklk/*k;k;l
lklkl*/
/*klklkl//klklkl*/
/*上述红色字体部分都是注释*/
main()
{
printf("here // should not be handled as comment");
printf("here /* .. */ should not be handled as comment");
}
状态转换图:
代码:
#include<stdio.h> #include<stdlib.h> #include<string.h> FILE * inputFile, *outputFile; int curState = 0; char curChar; char commentBuffer[10]=""; int bufferSize = 0; void handleCurChar() { switch(curState) { case 0: if(curChar == '/') { commentBuffer[bufferSize] = curChar; commentBuffer[++bufferSize] = '\0'; } else { fputc(curChar, outputFile); } break; case 1: if(curChar == '/' || curChar == '*') { commentBuffer[0] = '\0'; } else { fputs(commentBuffer, outputFile); commentBuffer[0] = '\0'; fputc(curChar, outputFile); } break; case 2: break; case 3: break; case 4: fputc(curChar, outputFile); break; case 5: break; case 6: if(curChar == '/') { commentBuffer[bufferSize] = curChar; commentBuffer[++ bufferSize] = '\0'; } else { printf("%c", fputc(curChar, outputFile)); } break; } } void changeState() { switch(curState) { case 0: if(curChar == '/') { curState = 1; } else if(curChar == '"') { curState = 4; } else { curState = 6; } break; case 1: if(curChar == '/') { curState = 2; } else if(curChar == '*') { curState = 3; } else if(curChar == '"') { curState = 4; } else { curState = 6; } break; case 2: if(curChar == '\n') { curState = 6; } else { curState = 2; } break; case 3: if(curChar == '*') { curState = 5; } else { curState = 3; } break; case 4: if(curChar == '"') { curState = 6; } else { curState = 4; } break; case 5: if(curChar == '/') { curState = 6; } else { curState = 3; } break; case 6: if(curChar == '/') { curState = 1; } else if(curChar == '"') { curState = 4; } else { curState = 6; } break; } } void clearComments() { while(!feof(inputFile)) { curChar = fgetc(inputFile); handleCurChar(); changeState(); } } int main(void){ printf("hello"); /*指向两个文件的指针*/ if((inputFile=fopen("1.txt","r"))==NULL) /*假如打不开的情况*/ { printf("File could not be opened\n"); } else if((outputFile=fopen("2.txt","w"))==NULL) { printf("File could not be opened\n"); } else /*打开之后引用函数*/ { clearComments(); } fclose(inputFile); /*关闭文件*/ fclose(outputFile); getchar(); return 0; }
时间: 2024-10-11 03:34:20