ソースからコメントを削除する2
CodeCompleteを読んでいたら、
- 設計とは決定論的なプロセスではなく、ヒューリスティックなプロセスである
- ソフトウェアの開発プロセスとは、そのソフトウェアに関する学習プロセスである
と書いてあった。一発で「良い」設計はできないということらしい。というわけで(?)設計というのもおこがましいが、この前書いたソースからコメントを削除するプログラムを早速改良してみた。流行の言葉でリファクタリングって言うのかしら。そんな大層なもんじゃないと思うけど。
/* A main function of this program.
* * 1. check args.
* * 2. open a specified file as an original source code.
* * 3. call delcmt() function, with 2 file streams.
* * The 1st file stream is original source code,
* * and the 2nd is stdout which the function write to.
* */
int main(int argc, char *argv[]){
FILE *fp = NULL;
int delcmt_result = 0; // check args
if(2 != argc){
printf("usage:%s src_file\n"
"This program outputs de-commented code of specified file"
" to STDOUT.\n", argv[0]);
return -1;
} // open an input file.
if (NULL == (fp = fopen(argv[1], "r"))){
fprintf(stderr, "can't open %s\n", argv[1]);
return -1;
} // output de-commented source code
delcmt_result = delcmt(fp, stdout); // close an input file.
fclose(fp); // return result value.
return delcmt_result;
} /* This function reads original source code from a p_in stream
* * and writes de-commented source code to a p_out stream.
* * This function does not delete blank line.
* * *** args ***
* * FILE *p_in :an original source code stream read from.
* * FILE *p_out:a de-commented source code stream write to.
* *
* * *** return ***
* * int : 0:OK
* * -1:NG
* *
* * *** output ***
* * This function writes de-commented source code to a file stream p_out.
* * So, if a p_out is stdout, de-comennted source code is output to STDOUT.
* * */
int delcmt(FILE *p_in, FILE *p_out){
int char0 = 0;
char state = NON_CMT; // check args
if(NULL == p_in || NULL == p_out){
fprintf(stderr, "delcmt error 0\n");
return -1;
} // get char from p_in file stream, and
// output only non-comment character
// until end of file stream,
// using 5 states.
while ( EOF != (char0 = fgetc(p_in))){
switch(state){
case NON_CMT:
state = non_cmt(char0, p_out);
break;
case CMT_SEMI_START:
state = cmt_semi_start(char0, p_out);
break;
case CPP_CMT:
state = cpp_cmt(char0, p_out);
break;
case C_CMT:
state = c_cmt(char0, p_out);
break;
case CMT_SEMI_END:
state = cmt_semi_end(char0, p_out);
break;
default:
goto error_end;
}
}
// check file stream is end.
if(!feof(p_in)){
goto error_end;
} return 0; error_end:
fprintf(stderr, "delcmt error 1\n");
return -1;
}
ポイントは3点。
- 各ステップにコメントを追加
- fclose()のポイントがおかしかったので修正。delcmt()関数を呼ぶ側でfcloseするようにした
- 各状態における処理を関数化
各関数についてはとりあえず省略。
| 固定リンク
この記事へのコメントは終了しました。


コメント