Mercurial > hg > toybox
comparison toys/other/dos2unix.c @ 653:2986aa63a021
Move commands into "posix", "lsb", and "other" menus/directories.
author | Rob Landley <rob@landley.net> |
---|---|
date | Sat, 25 Aug 2012 14:25:22 -0500 |
parents | toys/dos2unix.c@6a096902309d |
children | 6df4ccc0acbe |
comparison
equal
deleted
inserted
replaced
652:2d7c56913fda | 653:2986aa63a021 |
---|---|
1 /* vi: set sw=4 ts=4: | |
2 * | |
3 * dos2unix.c - convert newline format | |
4 * | |
5 * Copyright 2012 Rob Landley <rob@landley.net> | |
6 * | |
7 * No standard | |
8 | |
9 USE_DOS2UNIX(NEWTOY(dos2unix, NULL, TOYFLAG_BIN)) | |
10 USE_DOS2UNIX(OLDTOY(unix2dos, dos2unix, NULL, TOYFLAG_BIN)) | |
11 | |
12 config DOS2UNIX | |
13 bool "dos2unix/unix2dos" | |
14 default y | |
15 help | |
16 usage: dos2unix/unix2dos [file...] | |
17 | |
18 Convert newline format between dos (\r\n) and unix (just \n) | |
19 If no files listed copy from stdin, "-" is a synonym for stdin. | |
20 */ | |
21 | |
22 #include "toys.h" | |
23 | |
24 DEFINE_GLOBALS( | |
25 char *tempfile; | |
26 ) | |
27 | |
28 #define TT this.dos2unix | |
29 | |
30 static void do_dos2unix(int fd, char *name) | |
31 { | |
32 char c = toys.which->name[0]; | |
33 int outfd = 1, catch = 0; | |
34 | |
35 if (fd) outfd = copy_tempfile(fd, name, &TT.tempfile); | |
36 | |
37 for (;;) { | |
38 int len, in, out; | |
39 | |
40 len = read(fd, toybuf+(sizeof(toybuf)/2), sizeof(toybuf)/2); | |
41 if (len<0) { | |
42 perror_msg("%s",name); | |
43 toys.exitval = 1; | |
44 } | |
45 if (len<1) break; | |
46 | |
47 for (in = out = 0; in < len; in++) { | |
48 char x = toybuf[in+sizeof(toybuf)/2]; | |
49 | |
50 // Drop \r only if followed by \n in dos2unix mode | |
51 if (catch) { | |
52 if (c == 'u' || x != '\n') toybuf[out++] = '\r'; | |
53 catch = 0; | |
54 // Add \r only if \n not after \r in unix2dos mode | |
55 } else if (c == 'u' && x == '\n') toybuf[out++] = '\r'; | |
56 | |
57 if (x == '\r') catch++; | |
58 else toybuf[out++] = x; | |
59 } | |
60 xwrite(outfd, toybuf, out); | |
61 } | |
62 if (catch) xwrite(outfd, "\r", 1); | |
63 | |
64 if (fd) replace_tempfile(-1, outfd, &TT.tempfile); | |
65 } | |
66 | |
67 void dos2unix_main(void) | |
68 { | |
69 loopfiles(toys.optargs, do_dos2unix); | |
70 } |