3
0

dos2unix.c 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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 *temp_fn = temp_fn; /* for compiler */
  25. char *resolved_fn = resolved_fn;
  26. in = stdin;
  27. out = stdout;
  28. if (fn != NULL) {
  29. struct stat st;
  30. resolved_fn = xmalloc_follow_symlinks(fn);
  31. if (resolved_fn == NULL)
  32. bb_simple_perror_msg_and_die(fn);
  33. in = xfopen_for_read(resolved_fn);
  34. fstat(fileno(in), &st);
  35. temp_fn = xasprintf("%sXXXXXX", resolved_fn);
  36. i = mkstemp(temp_fn);
  37. if (i == -1
  38. || fchmod(i, st.st_mode) == -1
  39. ) {
  40. bb_simple_perror_msg_and_die(temp_fn);
  41. }
  42. out = xfdopen_for_write(i);
  43. }
  44. while ((i = fgetc(in)) != EOF) {
  45. if (i == '\r')
  46. continue;
  47. if (i == '\n')
  48. if (conv_type == CT_UNIX2DOS)
  49. fputc('\r', out);
  50. fputc(i, out);
  51. }
  52. if (fn != NULL) {
  53. if (fclose(in) < 0 || fclose(out) < 0) {
  54. unlink(temp_fn);
  55. bb_perror_nomsg_and_die();
  56. }
  57. xrename(temp_fn, resolved_fn);
  58. free(temp_fn);
  59. free(resolved_fn);
  60. }
  61. }
  62. int dos2unix_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  63. int dos2unix_main(int argc UNUSED_PARAM, char **argv)
  64. {
  65. int o, conv_type;
  66. /* See if we are supposed to be doing dos2unix or unix2dos */
  67. conv_type = CT_UNIX2DOS;
  68. if (applet_name[0] == 'd') {
  69. conv_type = CT_DOS2UNIX;
  70. }
  71. /* -u convert to unix, -d convert to dos */
  72. opt_complementary = "u--d:d--u"; /* mutually exclusive */
  73. o = getopt32(argv, "du");
  74. /* Do the conversion requested by an argument else do the default
  75. * conversion depending on our name. */
  76. if (o)
  77. conv_type = o;
  78. argv += optind;
  79. do {
  80. /* might be convert(NULL) if there is no filename given */
  81. convert(*argv, conv_type);
  82. } while (*++argv);
  83. return 0;
  84. }