//
// 郵便番号から住所を表示するプログラム
// 2023/05/03 作者:柴ONE
//
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
//https://www.post.japanpost.jp/zipcode/dl/oogaki-zip.html
//https://www.post.japanpost.jp/zipcode/dl/readme.html
void 郵便番号から住所表示(FILE *fp,char *郵便番号)
{
bool 検出 = false ;
char buf[BUFSIZ];
while (fgets(buf, BUFSIZ, fp) != NULL) {
char csv[10][128]; //csv[0]は捨てる
int ret = sscanf(buf,
"%[^,]," //csv[1] ,以外の単語,
"%[^,]," //csv[2]
"\"%[0-9]\"," //csv[3] "数字列",
"%[^,]," //csv[4]
"%[^,]," //csv[5]
"%[^,]," //csv[6]
"\"%[^,\"]\"," //csv[7] ",と\"以外の単語",
"\"%[^,\"]\"," //csv[8]
"\"%[^,\"]\"", //csv[9]
&csv[1][0],
&csv[2][0],
&csv[3][0], //郵便番号(7桁)
&csv[4][0],
&csv[5][0],
&csv[6][0],
&csv[7][0], //都道府県名
&csv[8][0], //市区町村名
&csv[9][0] //町域名
);
if(ret != 9){
fprintf(stderr,"形式異常 %s\n",buf);
continue;
}
if (strcmp(&csv[3][0], 郵便番号) != 0){
continue;
}
printf("住所:%s%s%s\n",
&csv[7][0],
&csv[8][0],
&csv[9][0]
);
検出 = true;
break;
}
if(!検出){
fprintf(stderr,"郵便番号 %s は見つかりませんでした\n",郵便番号);
}
}
void 郵便番号入力(char *postnum)
{
printf("郵便番号をハイフンなしで入れてね: ");
int ret = scanf("%s",postnum);
if(ret != 1){
fprintf(stderr,"郵便番号異常\n");
exit(1);
}
if(strlen(postnum) != 7){
fprintf(stderr,"郵便番号異常 %zu桁 != 7桁(%s)\n",
strlen(postnum),
postnum);
exit(1);
}
}
//KEN_ALL.CSVは Shift_JIS なので
// linuxの人は次の変換をしてね
// nkf -w KEN_ALL.CSV > KEN_ALL.CSV.utf8
// Windwosの人は
// "KEN_ALL.CSV.utf8"ではなくて"KEN_ALL.CSV"のままでOK
FILE *郵便番号データファイル(void)
{
const char *csvfilename = "KEN_ALL.CSV.utf8";
FILE *fp = fopen(csvfilename, "r");
if (fp == NULL){
fprintf(stderr,"%s 開かん\n",csvfilename);
exit(1);
}
return fp;
}
int main(void)
{
FILE *fp = 郵便番号データファイル();
char 郵便番号[128];
郵便番号入力(郵便番号);
郵便番号から住所表示(fp,郵便番号);
fclose(fp);
}