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#include "libbb.h"
32
33
34
35enum {
36 CT_UNIX2DOS = 1,
37 CT_DOS2UNIX
38};
39
40
41static void convert(char *fn, int conv_type)
42{
43 FILE *in, *out;
44 int i;
45 char *temp_fn = temp_fn;
46 char *resolved_fn = resolved_fn;
47
48 in = stdin;
49 out = stdout;
50 if (fn != NULL) {
51 struct stat st;
52
53 resolved_fn = xmalloc_follow_symlinks(fn);
54 if (resolved_fn == NULL)
55 bb_simple_perror_msg_and_die(fn);
56 in = xfopen_for_read(resolved_fn);
57 fstat(fileno(in), &st);
58
59 temp_fn = xasprintf("%sXXXXXX", resolved_fn);
60 i = xmkstemp(temp_fn);
61 if (fchmod(i, st.st_mode) == -1)
62 bb_simple_perror_msg_and_die(temp_fn);
63
64 out = xfdopen_for_write(i);
65 }
66
67 while ((i = fgetc(in)) != EOF) {
68 if (i == '\r')
69 continue;
70 if (i == '\n')
71 if (conv_type == CT_UNIX2DOS)
72 fputc('\r', out);
73 fputc(i, out);
74 }
75
76 if (fn != NULL) {
77 if (fclose(in) < 0 || fclose(out) < 0) {
78 unlink(temp_fn);
79 bb_perror_nomsg_and_die();
80 }
81 xrename(temp_fn, resolved_fn);
82 free(temp_fn);
83 free(resolved_fn);
84 }
85}
86
87int dos2unix_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
88int dos2unix_main(int argc UNUSED_PARAM, char **argv)
89{
90 int o, conv_type;
91
92
93 conv_type = CT_UNIX2DOS;
94 if (applet_name[0] == 'd') {
95 conv_type = CT_DOS2UNIX;
96 }
97
98
99 opt_complementary = "u--d:d--u";
100 o = getopt32(argv, "du");
101
102
103
104 if (o)
105 conv_type = o;
106
107 argv += optind;
108 do {
109
110 convert(*argv, conv_type);
111 } while (*argv && *++argv);
112
113 return 0;
114}
115