1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
| #include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#define MAXBUF 1024
#define MAXLINE 1024
#define D_FMODE 0666
#define D_DMODE 0777
int copie (int fs, int fd)
{
char buf[MAXBUF];
int n;
while ((n = read (fs, buf, MAXBUF)) > 0)
if (write (fd, buf, n) != n)
return -1;
return n; /* -1 ou 0 */
}
int copier (char source[], char dest[])
{
int fs, fd;
int n;
fs = open (source, O_RDONLY);
if (fs == -1)
return -1;
fd = open (dest, O_WRONLY | O_CREAT | O_TRUNC, D_FMODE);
if (fd == -1)
{
close (fs);
return -1;
}
n = copie (fs, fd);
close (fs);
close (fd);
return n;
}
int copier_arbre (char source[], char dest[]);
int copier_repertoire (char source[], char dest[])
{
DIR *dp;
struct dirent *d;
char *ps, *pd;
dp = opendir (source);
if (dp == NULL)
return -1;
if (mkdir (dest, D_DMODE) == -1)
return -1;
ps = source + strlen (source);
*ps++ = '/';
pd = dest + strlen (dest);
*pd++ = '/';
while ((d = readdir (dp)) != NULL)
{
if (d->d_ino != 0 && strcmp (d->d_name, ".") != 0 &&
strcmp (d->d_name, "..") != 0)
{
strcpy (ps, d->d_name);
strcpy (pd, d->d_name);
if (copier_arbre (source, dest) == -1)
return -1;
}
}
closedir (dp);
*(ps - 1) = *(pd - 1) = '\0';
return 0;
}
int copier_arbre (char source[], char dest[])
{
struct stat stbuf;
int n;
if (stat (source, &stbuf) == -1)
return -1;
switch (stbuf.st_mode & S_IFMT)
{
case S_IFREG:
n = copier (source, dest);
break;
case S_IFDIR:
n = copier_repertoire (source, dest);
break;
default:
fprintf (stderr, "%s : invalid file type\n", source);
n = -1;
break;
}
return n;
}
int main (int argc, char *argv[])
{
char source[MAXLINE], dest[MAXLINE];
if (argc != 3)
{
fprintf (stderr, "usage: %s <source> <dest>\n", argv[0]);
exit (1);
}
strcpy (source, argv[1]);
strcpy (dest, argv[2]);
if (copier_arbre (source, dest) == -1)
{
perror ("");
exit (1);
}
exit (0);
} |
Partager