09/05/23 17:07:20
>>151
// Usage: my_paste a1 b1 b2 b3 b4 ... > c1
// a: 行数はb(max)行 bの数と一致しない場合は途中まで処理する。
// b: 行数は1行のみ。改行で終わる。サイズは大きくても良い。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
FILE *inA, *inB, *outC = stdout;
char bufA[80]; // ファイルA読込用(1行を読込めるサイズが必要)
char bufB[256]; // ファイルB読込用(複数回に分けて読み込むので適当で良い)
int i, readsize;
if(argc < 3) return -1;
inA = fopen(argv[1], "r");
if (inA == NULL) { fprintf(stderr, "Can't open %s\n", argv[1]); exit(1); }
for (i = 0; i < argc-2; i++) {
inB = fopen(argv[i+2], "r");
if (inB == NULL) { fprintf(stderr, "Can't open %s\n", argv[i+2]); break; }
// Aを1行読込み、改行を取り除き、末尾にTabをつけてCに出力
if(fgets(bufA, sizeof(bufA), inA) == NULL) { fclose(inB); break; }
bufA[strlen(bufA) - 1] = 0;
fprintf(outC, "%s\t", bufA);
// Bをバッファサイズ単位で読込み、Cに追記する(必要な回数繰返す)
while ((readsize = fread(bufB, 1, sizeof(bufB), inB)) > 0) {
fwrite(bufB, 1, readsize, outC);
}
fclose(inB);
}
fclose(inA);
return 0;
}