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