Upload Tizen:Base source
[framework/base/util-linux-ng.git] / misc-utils / rename.c
1 /*
2  * rename.c - aeb 2000-01-01
3  *
4 --------------------------------------------------------------
5 #!/bin/sh
6 if [ $# -le 2 ]; then echo call: rename from to files; exit; fi
7 FROM="$1"
8 TO="$2"
9 shift
10 shift
11 for i in $@; do N=`echo "$i" | sed "s/$FROM/$TO/g"`; mv "$i" "$N"; done
12 --------------------------------------------------------------
13  * This shell script will do renames of files, but may fail
14  * in cases involving special characters. Here a C version.
15  */
16 #include <stdio.h>
17 #include <string.h>
18 #include <stdlib.h>
19 #include <errno.h>
20 #include "nls.h"
21
22 static char *progname;
23
24 static int
25 do_rename(char *from, char *to, char *s) {
26         char *newname, *where, *p, *q;
27         int flen, tlen, slen;
28
29         where = strstr(s, from);
30         if (where == NULL)
31                 return 0;
32
33         flen = strlen(from);
34         tlen = strlen(to);
35         slen = strlen(s);
36         newname = malloc(tlen+slen+1);
37         if (newname == NULL) {
38                 fprintf(stderr, _("%s: out of memory\n"), progname);
39                 exit(1);
40         }
41
42         p = s;
43         q = newname;
44         while (p < where)
45                 *q++ = *p++;
46         p = to;
47         while (*p)
48                 *q++ = *p++;
49         p = where+flen;
50         while (*p)
51                 *q++ = *p++;
52         *q = 0;
53
54         if (rename(s, newname) != 0) {
55                 int errsv = errno;
56                 fprintf(stderr, _("%s: renaming %s to %s failed: %s\n"),
57                                   progname, s, newname, strerror(errsv));
58                 exit(1);
59         }
60
61         return 1;
62 }
63
64 int
65 main(int argc, char **argv) {
66         char *from, *to, *p;
67         int i;
68
69         progname = argv[0];
70         if ((p = strrchr(progname, '/')) != NULL)
71                 progname = p+1;
72
73         setlocale(LC_ALL, "");
74         bindtextdomain(PACKAGE, LOCALEDIR);
75         textdomain(PACKAGE);
76
77         if (argc == 2) {
78                 if (!strcmp(argv[1], "-V") || !strcmp(argv[1], "--version")) {
79                         printf(_("%s (%s)\n"),
80                                progname, PACKAGE_STRING);
81                         return 0;
82                 }
83         }
84
85         if (argc < 3) {
86                 fprintf(stderr, _("call: %s from to files...\n"), progname);
87                 exit(1);
88         }
89
90         from = argv[1];
91         to = argv[2];
92
93         for (i=3; i<argc; i++)
94                 do_rename(from, to, argv[i]);
95         return 0;
96 }