数値の合計を求めるコマンドを作ってみた

exprとかawkとか使う方法は思い付いたけど
もっと簡単にできないかなぁと思って作ってみました。

環境

Mac OS X 10.8.1
gcc 4.2.1

準備

入力値の準備
$ cat input.txt
123                                                                                                                                                                              
10
232
111
301
コマンドの準備
$ gcc -o calc calc.c

実行

$ cat input.txt |./calc
777

$ seq 1 10 |./calc
55

ソースコード

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>

#define BUF_SIZE 512

int calc(char *read, int sum) {
    char *read_pos = read;
    char *new_pos;

    while (1) {
        new_pos = strchr(read_pos, '\n');
        if (new_pos == NULL) {
            memcpy(read, read_pos, BUF_SIZE * 2 - (read_pos - read) + 1);
            break;
        }

        *new_pos = '\0';
        ++new_pos;

        sum += atoi(read_pos);

        read_pos = new_pos;
    }

    return sum;
}

int main(int argc, char *const argv[]) {
    char buf[BUF_SIZE];
    char cache[BUF_SIZE * 2 + 1];
    int read_size = 0;
    int write_size = 0;
    int cache_size;
    int sum = 0;

    memset(cache, '\0', BUF_SIZE * 2 + 1);

    while (read_size = read(0, buf, BUF_SIZE)) {
        if (read_size == -1) {
            fprintf(stderr, "read error\n");
            return 1;
        }

        cache_size = strlen(cache);
        memcpy(cache + cache_size, buf, read_size);
        read_size = cache_size + read_size;

        sum += calc(cache, sum);
        if (strlen(cache) > BUF_SIZE) {
            fprintf(stderr, "record size over error\n");
            return 1;
        }
    }
    printf("%d", sum);

    return 0;
}

久々にC言語触った!自信ないw

まあこれからリファクタリングしつつ機能を拡張してみようかなと。
付けたいオプションもあるしね!



って、今こんなことしている暇ないんだった!!!

SphinxConJPの資料作成しないと><

試験前に掃除したくなる病ががが......