linux cp命令源码

本文转载自 http://www.csc.villanova.edu/~mdamian/C/stdc-file-copy.c


/*
 * stdc-file-copy.c - copy one file to a new location, possibly under a 
 * different name.
 */

#include <stdio.h>              /* standard input/output routines.    */

#define MAX_LINE_LEN 1000	/* maximal line length supported.     */

/*
 * function: main. copy the given source file to the given target file.
 * input:    path to source file and path to target file.
 * output:   target file is being created with identical contents to
 *           source file.
 */
void
main(int argc, char* argv[])
{
    char* file_path_from;	/* path to source file.   */
    char* file_path_to;		/* path to target file.   */
    FILE* f_from;		/* stream of source file. */
    FILE* f_to;			/* stream of target file. */
    char buf[MAX_LINE_LEN+1];   /* input buffer.          */

    /* read command line arguments */
    if (argc != 3 || !argv[1] || !argv[2]) {
	fprintf(stderr, "Usage: %s <source file path> <target file path>\n",
		argv[0]);
	exit(1);
    }
    file_path_from = argv[1];
    file_path_to = argv[2];

    /* open the source and the target files. */
    f_from = fopen(file_path_from, "r");
    if (!f_from) {
	fprintf(stderr, "Cannot open source file: ");
	perror("");
	exit(1);
    }
    f_to = fopen(file_path_to, "w+");
    if (!f_to) {
	fprintf(stderr, "Cannot open target file: ");
	perror("");
	exit(1);
    }

    /* copy source file to target file, line by line. */
    while (fgets(buf, MAX_LINE_LEN+1, f_from)) {
	if (fputs(buf, f_to) == EOF) {  /* error writing data */
	    fprintf(stderr, "Error writing to target file: ");
	    perror("");
	    exit(1);
	}
    }
    if (!feof(f_from)) { /* fgets failed _not_ due to encountering EOF */
        fprintf(stderr, "Error reading from source file: ");
        perror("");
        exit(1);
    }

    /* close source and target file streams. */
    if (fclose(f_from) == EOF) {
	fprintf(stderr, "Error when closing source file: ");
	perror("");
    }
    if (fclose(f_to) == EOF) {
	fprintf(stderr, "Error when closing target file: ");
	perror("");
    }
}


  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值