用於拷貝文件(文本文件或其餘類型的大型文件)的函數

// filecopier.c -- 拷貝文件
#include <stdio.h>

int file_copy(char *oldname, char *newname);

int main(void){
  char source[80], destination[80];
  
  //獲取源文件和目標文件文件名
  puts("\nEnter source file: ");
  gets(source);
  puts("\nEnter destination file: ");
  gets(destination);
  
  if(file_copy(source, destination) == 0)
    puts("Copy operation successful");
  else
    fprintf(stderr, "Error during copy operation");
  return 0;
} 

int file_copy(char *oldname, char *newname){
  FILE *fold, *fnew;
  int c;
  
  // 以二進制只讀模式打開源文件
  if((fold = fopen(oldname, "rb")) == NULL)
    return -1;
  
  // 以二進制寫入模式打開目標文件
  if((fnew = fopen(newname, "wb")) == NULL){
    fclose(fold);
    return -1;
  }
  
  /* 讀取源文件內容,一次讀取1字節,
   * 若是未達到文件末尾,
   * 將讀取內容寫入目標文件。 */
  
  while(1){
    c = fgetc(fold);
    
    if(!feof(fold))
      fputc(c, fnew);
    else
      break;
  }
  fclose(fnew);
  fclose(fold);
  
  return 0;
}
相關文章
相關標籤/搜索