Skip to content
On this page

mycopy.c


标签:代码片段C/unix  
c
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char const *argv[])
{
  /* 打开源文件 */
  FILE *input_file, *target_file;
  int c;

  if (argc != 3) {
    fprintf(stderr, "Usage: %s <source> <target>\n", argv[0]);
  }

  input_file = fopen(argv[1], "r");
  if (input_file == NULL) {
    perror("fopen()");
    exit(1);
  }
  /* 打开目标文件 */
  target_file = fopen(argv[2], "w");
  if(target_file == NULL) {
    fclose(input_file);
    perror("fopen()");
    exit(1);
  }
  /* or while(1) 判断 c == EOF break 循环*/
  /* or while(c = fgets(file) != EOF) */
  while (!feof(input_file)) {
    c = fgetc(input_file);
    putc(c, target_file);
  }
  fputc('\n', target_file);
  exit(0);
}

程序参考:https://www.bilibili.com/video/BV1wd4y137fd/?p=8

这个程序挺简单,但还是比较有细节值得学习的:

  • fopen 打开文件后,是否判断它为 NULL

Last updated: