1
2
3
4
5
6
7
8
9
10
11
12
13
14
15#include "libbb.h"
16
17enum {
18 CT_UNIX2DOS = 1,
19 CT_DOS2UNIX
20};
21
22
23static void convert(char *fn, int conv_type)
24{
25 FILE *in, *out;
26 int i;
27 char *temp_fn = temp_fn;
28 char *resolved_fn = resolved_fn;
29
30 in = stdin;
31 out = stdout;
32 if (fn != NULL) {
33 struct stat st;
34
35 resolved_fn = xmalloc_follow_symlinks(fn);
36 if (resolved_fn == NULL)
37 bb_simple_perror_msg_and_die(fn);
38 in = xfopen_for_read(resolved_fn);
39 fstat(fileno(in), &st);
40
41 temp_fn = xasprintf("%sXXXXXX", resolved_fn);
42 i = mkstemp(temp_fn);
43 if (i == -1
44 || fchmod(i, st.st_mode) == -1
45 || !(out = fdopen(i, "w+"))
46 ) {
47 bb_simple_perror_msg_and_die(temp_fn);
48 }
49 }
50
51 while ((i = fgetc(in)) != EOF) {
52 if (i == '\r')
53 continue;
54 if (i == '\n')
55 if (conv_type == CT_UNIX2DOS)
56 fputc('\r', out);
57 fputc(i, out);
58 }
59
60 if (fn != NULL) {
61 if (fclose(in) < 0 || fclose(out) < 0) {
62 unlink(temp_fn);
63 bb_perror_nomsg_and_die();
64 }
65 xrename(temp_fn, resolved_fn);
66 free(temp_fn);
67 free(resolved_fn);
68 }
69}
70
71int dos2unix_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
72int dos2unix_main(int argc, char **argv)
73{
74 int o, conv_type;
75
76
77 conv_type = CT_UNIX2DOS;
78 if (applet_name[0] == 'd') {
79 conv_type = CT_DOS2UNIX;
80 }
81
82
83 opt_complementary = "u--d:d--u";
84 o = getopt32(argv, "du");
85
86
87
88 if (o)
89 conv_type = o;
90
91 do {
92
93 convert(argv[optind], conv_type);
94 optind++;
95 } while (optind < argc);
96
97 return 0;
98}
99