20131023【C言語】ファイルを一行ずつ確認しながらよみこむ

お題

ファイルを一行ずつ確認しながらよみこむ

 

プログラム概要

ファイルを読み込み一行ずつ表示する

その際、表示するかどうかを問い合わせる

 

ソース

#include <stdio.h>

#include <stdlib.h>

#include <ctype.h>

 

int main(int argc, char *argv[])

{

FILE *fp;

char str[80];

char ch;

 

/* Check arguments */

if (argc != 2) {

fprintf(stderr, "Cannot open %s.\n", argv[1]);

exit(1);

}

 

/* Open file */

if *1 == NULL ) {

fprintf(stderr, "Error while open %s.\n", argv[1]);

exit(1);

}

 

/* Read file till user stops */

while(!feof(fp)) {

fgets(str, 79, fp);

if(ferror(fp)) {

fprintf(stderr, "Error read file.\n");

exit(1);

}

 

if(!feof(fp)) 

printf("%s", str);

else

break;

 

        printf("Do you continue? (y/n):");

scanf("%c", &ch);

(void)getchar();

 

        if (toupper(ch) != 'Y')

            break;

}

 

/* Close file */

if (fclose(fp) == EOF) {

fprintf(stderr, "Error while close file.\n");

exit(1);

}

 

return 0;

}

 

実行結果

# ./a.out myfile.txt 

hoge

Do you continue? (y/n):y

gege

Do you continue? (y/n):n

 

*1:fp = fopen(argv[1], "rb"