2013年12月6日金曜日

開発環境

C実践プログラミング 第3版 (Steve Oualline (著)、 望月 康司 (監訳) (翻訳)、谷口 功 (翻訳)、オライリー・ジャパン)のⅡ部(単純なプログラミング)の14章(ファイル入出力)、14.1(ファイル関数)、14.2(変換ルーチン)、14.3(バイナリファイルとASCIIファイル)、14.4(行終端にまつわる謎)、14.5(バイナリI/O)、14.6(バッファリングの問題)、14.7(バッファリングを行わないI/O)、14.8(ファイル形式の設計)、14.10(プログラミング実習)、実習 14-6を解いてみる。

その他参考書籍

実習14-6.

ファイル構成仕様ファイル

郵便番号 (7桁の数字)
住所
名前
その他の情報

ファイルの例

sample.txt

ファイル  構成仕様ファイル V1.0
1234567   郵便番号(7桁の数字)
Japan     住所
kamimura 名前
other     その他の情報

コード

sample.c

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

struct mailing {
    int zip;
    char address[100];
    char name[100];
    char other[100];
};

int main(int argc, char *argv[])
{
    struct mailing *p;
    char ch;
    struct mailing m;
    int flag = 1;
    FILE *in_file;
    FILE *out_file;
    void readline(FILE *fp, char s[]);
    
    if (argc != 3){
        fprintf(stderr, "Error: Wrong number of arguments\n");
        fprintf(stderr, "Usage is: sample <in> <out>\n");
        exit (8);
    }
    in_file = fopen(argv[1], "r");
    if (in_file == NULL){
        fprintf(stderr, "Cannot open %s\n", argv[1]);
        exit (8);
    }
    out_file = fopen(argv[2], "w");
    if (out_file == NULL){
        fprintf(stderr, "Cannot open %s\n", argv[2]);
        exit (8);
    }
    while (1){
        ch = fgetc(in_file);
        if (ch == '\n'){
            break;
        }
    }
    m.zip = 0;
    while (1){
        ch = fgetc(in_file);
        if (ch == '\n'){
            break;
        } else if (flag){
            if (isdigit(ch)){
                m.zip = m.zip * 10 + (ch - '0');
            } else {
                flag = 0;
            }
        }
    }
    readline(in_file, m.address);
    readline(in_file, m.name);
    readline(in_file, m.other);
    fprintf(out_file, "郵便番号: %d\n住所: %s\n名前: %s\nその他の情報: %s\n",
        m.zip, m.address, m.name, m.other);
    fclose(in_file);
    fclose(out_file);
    return (0);
}

void readline(FILE *fp, char s[])
{
    char ch;
    int i = 0;
    int flag = 1;
    while (1){
        ch = fgetc(fp);
        if (ch == '\n' || ch == EOF){
            break;
        } else if (flag){
            if (ch != ' '){
                s[i] = ch;
                i++;
            } else {
                flag = 0;
            }
        }
    }
    s[i] = '\0';
}

makefile

CC=cc
CFLAGS=-g

sample: sample.c
 $(CC) $(CFLAGS) -o sample sample.c

clean:
 rm -f sample

入出力結果(Terminal)

$ make
cc -g -o sample sample.c
$ ./sample sample.txt sample.txt.out
$ cat sample.txt.out
郵便番号: 1234567
住所: Japan
名前: kamimura
その他の情報: other
$

0 コメント:

コメントを投稿