1. コマンドラインで指定されたファイル(テキストまたはバイナリ)のバイト数を数え、その結果を表示するプログラムを作成してください。
#include
#include
int main(int argc, char *argv[])
{
FILE *fp;
long count = 0;
char ch;
if (argc != 2) {
printf("Usage: %s \n", argv[0]);
exit(1);
}
if ((fp = fopen(argv[1], "rb")) == NULL) {
printf("Channot open file: %s\n", argv[1]);
exit(1);
}
while (!feof(fp)) {
ch = fgetc(fp);
if (ferror(fp)) {
printf("Error: at reading file.\n");
exit(1);
}
count++;
}
if (fclose(fp) == EOF) {
printf("Error: at closing file.\n");
exit(1);
}
printf("%ld bytes\n", count - 1);
return 0;
}
出力部分で – 1 しているのは、EOF も数えてしまっているから、それを差し引いている。
実行例:
takatoh@nightschool $ ./practice_9_3_1 sample_9_3 8925 bytes takatoh@nightschool $ ls -l sample_9_3 -rwxrwxr-x 1 takatoh takatoh 8925 5月 10 19:11 sample_9_3