dos2unix.c 1.6 KB

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