1 /* dos2unix.c - convert newline format
2  *
3  * Copyright 2012 Rob Landley <rob@landley.net>
4 
5 USE_DOS2UNIX(NEWTOY(dos2unix, 0, TOYFLAG_BIN))
6 USE_UNIX2DOS(NEWTOY(unix2dos, 0, TOYFLAG_BIN))
7 
8 config DOS2UNIX
9   bool "dos2unix/unix2dos"
10   default y
11   help
12     usage: dos2unix [FILE...]
13 
14     Convert newline format from dos "\r\n" to unix "\n".
15     If no files listed copy from stdin, "-" is a synonym for stdin.
16 
17 config UNIX2DOS
18   bool "unix2dos"
19   default y
20   help
21     usage: unix2dos [FILE...]
22 
23     Convert newline format from unix "\n" to dos "\r\n".
24     If no files listed copy from stdin, "-" is a synonym for stdin.
25 */
26 
27 #define FOR_dos2unix
28 #include "toys.h"
29 
GLOBALS(char * tempfile;)30 GLOBALS(
31   char *tempfile;
32 )
33 
34 static void do_dos2unix(int fd, char *name)
35 {
36   char c = toys.which->name[0];
37   int outfd = 1, catch = 0;
38 
39   if (fd) outfd = copy_tempfile(fd, name, &TT.tempfile);
40 
41   for (;;) {
42     int len, in, out;
43 
44     len = read(fd, toybuf+(sizeof(toybuf)/2), sizeof(toybuf)/2);
45     if (len<0) perror_msg_raw(name);
46     if (len<1) break;
47 
48     for (in = out = 0; in < len; in++) {
49       char x = toybuf[in+sizeof(toybuf)/2];
50 
51       // Drop \r only if followed by \n in dos2unix mode
52       if (catch) {
53         if (c == 'u' || x != '\n') toybuf[out++] = '\r';
54         catch = 0;
55       // Add \r only if \n not after \r in unix2dos mode
56       } else if (c == 'u' && x == '\n') toybuf[out++] = '\r';
57 
58       if (x == '\r') catch++;
59       else toybuf[out++] = x;
60     }
61     xwrite(outfd, toybuf, out);
62   }
63   if (catch) xwrite(outfd, "\r", 1);
64 
65   if (fd) replace_tempfile(-1, outfd, &TT.tempfile);
66 }
67 
dos2unix_main(void)68 void dos2unix_main(void)
69 {
70   loopfiles(toys.optargs, do_dos2unix);
71 }
72 
unix2dos_main(void)73 void unix2dos_main(void)
74 {
75   dos2unix_main();
76 }
77