#include <sys/cdefs.h>
#ifndef lint
__COPYRIGHT(
"@(#) Copyright (c) 1988, 1993, 1994\
The Regents of the University of California. All rights reserved.");
#endif /* not lint */
#ifndef lint
#if 0
static char sccsid[] = "@(#)cp.c 8.5 (Berkeley) 4/29/95";
#else
__RCSID("$NetBSD: cp.c,v 1.58 2012/01/04 15:58:37 christos Exp $");
#endif
#endif /* not lint */
/*
* Cp copies source files to target files.
*
* The global PATH_T structure "to" always contains the path to the
* current target file. Since fts(3) does not change directories,
* this path can be either absolute or dot-relative.
*
* The basic algorithm is to initialize "to" and use fts(3) to traverse
* the file hierarchy rooted in the argument list. A trivial case is the
* case of 'cp file1 file2'. The more interesting case is the case of
* 'cp file1 file2 ... fileN dir' where the hierarchy is traversed and the
* path (relative to the root of the traversal) is appended to dir (stored
* in "to") to form the final target path.
*/
#include <sys/param.h>
#include <sys/stat.h>
#include <assert.h>
#include <err.h>
#include <errno.h>
#include <fts.h>
#include <locale.h>
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "extern.h"
#define STRIP_TRAILING_SLASH(p) { \
while ((p).p_end > (p).p_path + 1 && (p).p_end[-1] == '/') \
*--(p).p_end = '\0'; \
}
static char empty[] = "";
PATH_T to = { .p_end = to.p_path, .target_end = empty };
uid_t myuid;
int Hflag, Lflag, Rflag, Pflag, fflag, iflag, lflag, pflag, rflag, vflag, Nflag;
mode_t myumask;
sig_atomic_t pinfo;
enum op { FILE_TO_FILE, FILE_TO_DIR, DIR_TO_DNE };
static int copy(char *[], enum op, int);
static void
progress(int sig __unused)
{
pinfo++;
}
int
cp_main(int argc, char *argv[])
{
struct stat to_stat, tmp_stat;
enum op type;
int ch, fts_options, r, have_trailing_slash;
char *target, **src;
#ifndef ANDROID
setprogname(argv[0]);
#endif
(void)setlocale(LC_ALL, "");
Hflag = Lflag = Pflag = Rflag = 0;
while ((ch = getopt(argc, argv, "HLNPRfailprv")) != -1)
switch (ch) {
case 'H':
Hflag = 1;
Lflag = Pflag = 0;
break;
case 'L':
Lflag = 1;
Hflag = Pflag = 0;
break;
case 'N':
Nflag = 1;
break;
case 'P':
Pflag = 1;
Hflag = Lflag = 0;
break;
case 'R':
Rflag = 1;
break;
case 'a':
Pflag = 1;
pflag = 1;
Rflag = 1;
Hflag = Lflag = 0;
break;
case 'f':
fflag = 1;
iflag = 0;
break;
case 'i':
iflag = isatty(fileno(stdin));
fflag = 0;
break;
case 'l':
lflag = 1;
break;
case 'p':
linux下cp命令---C代码实现
于 2017-09-27 17:48:22 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)