1 /* vi: set sw=4 ts=4: */
5 * dos2unix '\n' convertor 0.5.0
6 * based on Unix2Dos 0.9.0 by Peter Hanecak (made 19.2.1997)
7 * Copyright 1997,.. by Peter Hanecak <hanecak@megaloman.sk>.
10 * dos2unix filters reading input from stdin and writing output to stdout.
12 * Licensed under GPLv2 or later, see file LICENSE in this source tree.
15 //usage:#define dos2unix_trivial_usage
16 //usage: "[-ud] [FILE]"
17 //usage:#define dos2unix_full_usage "\n\n"
18 //usage: "Convert FILE in-place from DOS to Unix format.\n"
19 //usage: "When no file is given, use stdin/stdout.\n"
21 //usage: "\n -u dos2unix"
22 //usage: "\n -d unix2dos"
24 //usage:#define unix2dos_trivial_usage
25 //usage: "[-ud] [FILE]"
26 //usage:#define unix2dos_full_usage "\n\n"
27 //usage: "Convert FILE in-place from Unix to DOS format.\n"
28 //usage: "When no file is given, use stdin/stdout.\n"
30 //usage: "\n -u dos2unix"
31 //usage: "\n -d unix2dos"
35 /* This is a NOEXEC applet. Be very careful! */
42 /* if fn is NULL then input is stdin and output is stdout */
43 static void convert(char *fn, int conv_type)
47 char *temp_fn = temp_fn; /* for compiler */
48 char *resolved_fn = resolved_fn;
55 resolved_fn = xmalloc_follow_symlinks(fn);
56 if (resolved_fn == NULL)
57 bb_simple_perror_msg_and_die(fn);
58 in = xfopen_for_read(resolved_fn);
59 fstat(fileno(in), &st);
61 temp_fn = xasprintf("%sXXXXXX", resolved_fn);
62 i = xmkstemp(temp_fn);
63 if (fchmod(i, st.st_mode) == -1)
64 bb_simple_perror_msg_and_die(temp_fn);
66 out = xfdopen_for_write(i);
69 while ((i = fgetc(in)) != EOF) {
73 if (conv_type == CT_UNIX2DOS)
79 if (fclose(in) < 0 || fclose(out) < 0) {
81 bb_perror_nomsg_and_die();
83 xrename(temp_fn, resolved_fn);
89 int dos2unix_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
90 int dos2unix_main(int argc UNUSED_PARAM, char **argv)
94 /* See if we are supposed to be doing dos2unix or unix2dos */
95 conv_type = CT_UNIX2DOS;
96 if (applet_name[0] == 'd') {
97 conv_type = CT_DOS2UNIX;
100 /* -u convert to unix, -d convert to dos */
101 opt_complementary = "u--d:d--u"; /* mutually exclusive */
102 o = getopt32(argv, "du");
104 /* Do the conversion requested by an argument else do the default
105 * conversion depending on our name. */
111 /* might be convert(NULL) if there is no filename given */
112 convert(*argv, conv_type);
113 } while (*argv && *++argv);