コードは、ddd.ddd.ddd.ddd パターンを探してファイルを移動できます。
"%d"
or"%u"
は先頭のスペースを受け入れるため、 and の'-'
使用は避けて'+'
ください。
疑似コード
Read from a file until EOF found
repeatedly look for a digit
if it is found
note position
put digit back into stream
look for ddd.ddd.ddd.ddd
if found
decode (and test for values > 255)
if successful return result
go back to position
return fail value;
サンプルコード。IO エラー チェックも必要です。
unsigned long Parse_IP(FILE *inf) {
int ch;
for ((ch = fgetc(inf)) != EOF) {
if (isdigit(ch)) {
long pos = ftell(inf);
ungetc(ch, inf);
char buf[4][4];
int count = fscanf(inf, "%3[0-9].%3[0-9].%3[0-9].%3[0-9]",
buf[0], buf[1], buf[2], buf[3]);
if (count == 4) {
unsigned long ip = 0;
int i;
for (i=0; i<4; i++) {
int digit = atoi(buf[i]);
if (digit > 255) break;
ip = ip*256 + digit;
}
if (i == 4) return ip;
}
fseek(inf, pos, SEEK_SET);
}
}
return 0;
}
使用例
unsigned long ip;
while ((ip = Parse_IP(inf)) != 0) {
printf("ip %08lX\n", ip);
}