iscntrl関数は、指定された文字が制御文字(コントロール文字)かを調べます。制御字文字はASCII文字セットの場合、’0x00’~’0x1F’と’0x7F’の33文字です。
#include <ctype.h>
int iscntrl(int c);
cは、チェックしたい文字を指定します。int型ですので注意してください。
戻り値として、引数の値が制御文字であれば0以外を、そうでなければ0を返します。
プログラム 例
#include <stdio.h>
#include <ctype.h>
int main(void)
{
FILE *fp;
char in_file[100]; /* 入力ファイル */
int in_data; /* 入力データ */
int ctrl_cnt = 0; /* 制御文字の個数 */
int other_cnt = 0; /* 制御文字以外の個数 */
int return_code = 0; /* リターンコード */
printf('入力ファイルのパス名を入力してください ==> ');
scanf('%s', &in_file);
if ((fp = fopen(in_file, 'r')) != NULL) {
while ((in_data = getc(fp)) != EOF) {
/* in_dataの値が制御文字だったら0以外が返る */
if (iscntrl(in_data) != 0) {
++ctrl_cnt; /* 制御文字数のカウントアップ */
}
else {
++other_cnt; /* 制御文字以外の数のカウントアップ */
}
}
fclose(fp);
/* 結果の表示 */
printf('制御文字 :%5d\n', ctrl_cnt);
printf('制御文字以外:%5d\n', other_cnt);
printf('合計 :%5d\n', ctrl_cnt + other_cnt);
}
else {
return_code = 1;
}
return return_code;
}
例の実行結果
$ wc -lc iscntrl.c # 行数とバイト数を表示 37 1114 iscntrl.c $ ./iscntrl.exe 入力ファイルのパス名を入力してください ==> iscntrl.c 制御文字 : 37 制御文字以外: 1077 合計 : 1114 $