3
0

dos2unix.c 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * dos2unix for BusyBox
  4. *
  5. * dos2unix '\n' convertor 0.5.0
  6. * based on Unix2Dos 0.9.0 by Peter Hanecak (made 19.2.1997)
  7. * Copyright 1997,.. by Peter Hanecak <hanecak@megaloman.sk>.
  8. * All rights reserved.
  9. *
  10. * dos2unix filters reading input from stdin and writing output to stdout.
  11. *
  12. * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
  13. */
  14. #include "libbb.h"
  15. enum {
  16. CT_UNIX2DOS = 1,
  17. CT_DOS2UNIX
  18. };
  19. /* if fn is NULL then input is stdin and output is stdout */
  20. static void convert(char *fn, int conv_type)
  21. {
  22. FILE *in, *out;
  23. int i;
  24. char *name_buf = name_buf; /* for compiler */
  25. in = stdin;
  26. out = stdout;
  27. if (fn != NULL) {
  28. in = xfopen(fn, "r");
  29. /*
  30. The file is then created with mode read/write and
  31. permissions 0666 for glibc 2.0.6 and earlier or
  32. 0600 for glibc 2.0.7 and later.
  33. */
  34. name_buf = xasprintf("%sXXXXXX", fn);
  35. i = mkstemp(name_buf);
  36. if (i == -1
  37. || fchmod(i, 0600) == -1
  38. || !(out = fdopen(i, "w+"))
  39. ) {
  40. bb_perror_nomsg_and_die();
  41. }
  42. }
  43. while ((i = fgetc(in)) != EOF) {
  44. if (i == '\r')
  45. continue;
  46. if (i == '\n')
  47. if (conv_type == CT_UNIX2DOS)
  48. fputc('\r', out);
  49. fputc(i, out);
  50. }
  51. if (fn != NULL) {
  52. if (fclose(in) < 0 || fclose(out) < 0) {
  53. unlink(name_buf);
  54. bb_perror_nomsg_and_die();
  55. }
  56. // TODO: destroys symlinks. See how passwd handles this
  57. xrename(name_buf, fn);
  58. free(name_buf);
  59. }
  60. }
  61. int dos2unix_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  62. int dos2unix_main(int argc, char **argv)
  63. {
  64. int o, conv_type;
  65. /* See if we are supposed to be doing dos2unix or unix2dos */
  66. conv_type = CT_UNIX2DOS;
  67. if (applet_name[0] == 'd') {
  68. conv_type = CT_DOS2UNIX;
  69. }
  70. /* -u convert to unix, -d convert to dos */
  71. opt_complementary = "u--d:d--u"; /* mutually exclusive */
  72. o = getopt32(argv, "du");
  73. /* Do the conversion requested by an argument else do the default
  74. * conversion depending on our name. */
  75. if (o)
  76. conv_type = o;
  77. do {
  78. /* might be convert(NULL) if there is no filename given */
  79. convert(argv[optind], conv_type);
  80. optind++;
  81. } while (optind < argc);
  82. return 0;
  83. }