ページ 11

ファイルのコピーについて

Posted: 2016年9月25日(日) 00:48
by おーばー

コード:

  #include<stdio.h>
  #include<string.h>
  #include<stdlib.h>
  
  const int SIZE=256;
  
  int main(int argc,char *argv[]){
      FILE *destination_file;
      FILE *source_file;
      char buffer[SIZE];
      char str[SIZE];
      char source_name[SIZE];
      char destination_name[SIZE];
      char *ptr;
      int number,i;
      
      if(argc!=2+1){
          fprintf(stderr,"コマンドライン引数が足りません ex) test src dest %d",argc);
          exit(4);
      }
      strcpy(source_name,argv[1]);
      strcpy(destination_name,argv[2]);
      
      source_file=fopen(source_name,"r");
      destination_file=fopen(destination_name,"w");
      
      while(1){
          int err_print;
          char *err_scan;
          
          err_scan=fgets(buffer,sizeof(buffer),source_file);
          
          /*if(err_scan==NULL){
              fprintf(stderr,"ファイルのコピー時にエラーが発生しました\n");
              exit(5);
          }*/
          if(err_scan==NULL){
              break;
          }
          err_print=fprintf(destination_file,"%s",buffer);
      }
      printf("ファイルのコピーに成功しました");
      return 0;
  }
上記のプログラムにおいてのエラー処理?についてです
fgets関数で文字の読み込み時のエラーとテキストファイルを読み込み終わった時の分け方について教えていただきたいです

自分としては今のようなfgets関数でエラー=読み込めなかった≒テキストファイルの内容をすべて読みこんだ よって終了,のような動作を
fgets関数でエラー⇒fprintf(stderr,"文字取得時にエラーが発生しました\n");exit(5);
fgets関数でテキストファイルの文字を読み込み終わった⇒printf("ファイルのコピーに成功しました\n");のようにしたいです

Re: ファイルのコピーについて

Posted: 2016年9月25日(日) 05:05
by YuO
fgetsがNULLを返した場合に,feof関数やferror関数を使って判断すれば良いかと思います。