20131015【C言語】ftellを使う
お題
ftellを使う
プログラム処理概要
- コマンドライン引数でインプットファイルとアウトプットファイルを指定
- これら2つのファイルを開く
- インプットファイルの終端に移動する
- 終端から先頭に向って逆にアウトプットファイルにコピーする
- ファイルを閉じる
ソース
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
long loc;
FILE *in, *out;
char ch;
/* Check argument */
if (argc != 3) {
fprintf(stderr, "Usage: <Program Name> <Source File> <Target File>.\n");
exit(1);
}
if *1 == NULL) {
fprintf(stderr, "Cannot open file %s.\n", argv[1]);
exit(1);
}
if *2 == NULL) {
fprintf(stderr, "Cannot open file %s.\n", argv[2]);
exit(1);
}
/* Reach end of file */
fseek(in, 0L, SEEK_END);
loc = ftell(in);
/* Copy file by reverse */
loc = loc - 2;/* Back from end of file */
while (loc >= 0L) {
fseek(in, loc, SEEK_SET);
ch = fgetc(in);
fputc(ch, out);
loc--;
}
fclose(in);
fclose(out);
return 0;
}
実行結果
# cat in.txt
abcde
fghij
# ./a.out in.txt out.txt
# cat out.txt
jihgf
edcba