1 /* dos2unix.c - convert newline format
3 * Copyright 2012 Rob Landley <rob@landley.net>
5 USE_DOS2UNIX(NEWTOY(dos2unix, 0, TOYFLAG_BIN))
6 USE_UNIX2DOS(NEWTOY(unix2dos, 0, TOYFLAG_BIN))
9 bool "dos2unix/unix2dos"
12 usage: dos2unix [FILE...]
14 Convert newline format from dos "\r\n" to unix "\n".
15 If no files listed copy from stdin, "-" is a synonym for stdin.
21 usage: unix2dos [FILE...]
23 Convert newline format from unix "\n" to dos "\r\n".
24 If no files listed copy from stdin, "-" is a synonym for stdin.
34 static void do_dos2unix(int fd, char *name)
36 char c = toys.which->name[0];
37 int outfd = 1, catch = 0;
39 if (fd) outfd = copy_tempfile(fd, name, &TT.tempfile);
44 len = read(fd, toybuf+(sizeof(toybuf)/2), sizeof(toybuf)/2);
45 if (len<0) perror_msg_raw(name);
48 for (in = out = 0; in < len; in++) {
49 char x = toybuf[in+sizeof(toybuf)/2];
51 // Drop \r only if followed by \n in dos2unix mode
53 if (c == 'u' || x != '\n') toybuf[out++] = '\r';
55 // Add \r only if \n not after \r in unix2dos mode
56 } else if (c == 'u' && x == '\n') toybuf[out++] = '\r';
58 if (x == '\r') catch++;
59 else toybuf[out++] = x;
61 xwrite(outfd, toybuf, out);
63 if (catch) xwrite(outfd, "\r", 1);
65 if (fd) replace_tempfile(-1, outfd, &TT.tempfile);
68 void dos2unix_main(void)
70 loopfiles(toys.optargs, do_dos2unix);
73 void unix2dos_main(void)