]>
Commit | Line | Data |
---|---|---|
b493aa03 CF |
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 | #ifndef HAVE_locale_h | |
17 | #define HAVE_locale_h | |
18 | #endif | |
19 | #include <stdio.h> | |
20 | #include <string.h> | |
21 | #include <stdlib.h> | |
22 | #include <errno.h> | |
23 | #include "nls.h" | |
24 | ||
25 | #ifndef util_linux_version | |
26 | #define util_linux_version "util-linux-2.11y" | |
27 | #endif | |
28 | ||
29 | static char *progname; | |
30 | ||
31 | static int | |
32 | do_rename(char *from, char *to, char *s) { | |
33 | char *newname, *where, *p, *q; | |
34 | int flen, tlen, slen; | |
35 | ||
36 | where = strstr(s, from); | |
37 | if (where == NULL) | |
38 | return 0; | |
39 | ||
40 | flen = strlen(from); | |
41 | tlen = strlen(to); | |
42 | slen = strlen(s); | |
43 | newname = malloc(tlen+slen+1); | |
44 | if (newname == NULL) { | |
45 | fprintf(stderr, _("%s: out of memory\n"), progname); | |
46 | exit(1); | |
47 | } | |
48 | ||
49 | p = s; | |
50 | q = newname; | |
51 | while (p < where) | |
52 | *q++ = *p++; | |
53 | p = to; | |
54 | while (*p) | |
55 | *q++ = *p++; | |
56 | p = where+flen; | |
57 | while (*p) | |
58 | *q++ = *p++; | |
59 | *q = 0; | |
60 | ||
61 | if (rename(s, newname) != 0) { | |
62 | int errsv = errno; | |
63 | fprintf(stderr, _("%s: renaming %s to %s failed: %s\n"), | |
64 | progname, s, newname, strerror(errsv)); | |
65 | exit(1); | |
66 | } | |
67 | ||
68 | return 1; | |
69 | } | |
70 | ||
71 | int | |
72 | main(int argc, char **argv) { | |
73 | char *from, *to, *p; | |
74 | int i, ct; | |
75 | ||
76 | progname = argv[0]; | |
77 | if ((p = strrchr(progname, '/')) != NULL) | |
78 | progname = p+1; | |
79 | ||
80 | setlocale(LC_ALL, ""); | |
81 | bindtextdomain(PACKAGE, LOCALEDIR); | |
82 | textdomain(PACKAGE); | |
83 | ||
84 | if (argc == 2) { | |
85 | if (!strcmp(argv[1], "-V") || !strcmp(argv[1], "--version")) { | |
86 | printf(_("%s from %s\n"), | |
87 | progname, util_linux_version); | |
88 | return 0; | |
89 | } | |
90 | } | |
91 | ||
92 | if (argc < 3) { | |
93 | fprintf(stderr, _("call: %s from to files...\n"), progname); | |
94 | exit(1); | |
95 | } | |
96 | ||
97 | from = argv[1]; | |
98 | to = argv[2]; | |
99 | ||
100 | ct = 0; | |
101 | for (i=3; i<argc; i++) | |
102 | ct += do_rename(from, to, argv[i]); | |
103 | return 0; | |
104 | } |