3
0

dos2unix.c 2.2 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 GPLv2 or later, see file LICENSE in this source tree.
  13. */
  14. #include "libbb.h"
  15. /* This is a NOEXEC applet. Be very careful! */
  16. enum {
  17. CT_UNIX2DOS = 1,
  18. CT_DOS2UNIX
  19. };
  20. /* if fn is NULL then input is stdin and output is stdout */
  21. static void convert(char *fn, int conv_type)
  22. {
  23. FILE *in, *out;
  24. int i;
  25. char *temp_fn = temp_fn; /* for compiler */
  26. char *resolved_fn = resolved_fn;
  27. in = stdin;
  28. out = stdout;
  29. if (fn != NULL) {
  30. struct stat st;
  31. resolved_fn = xmalloc_follow_symlinks(fn);
  32. if (resolved_fn == NULL)
  33. bb_simple_perror_msg_and_die(fn);
  34. in = xfopen_for_read(resolved_fn);
  35. fstat(fileno(in), &st);
  36. temp_fn = xasprintf("%sXXXXXX", resolved_fn);
  37. i = xmkstemp(temp_fn);
  38. if (fchmod(i, st.st_mode) == -1)
  39. bb_simple_perror_msg_and_die(temp_fn);
  40. out = xfdopen_for_write(i);
  41. }
  42. while ((i = fgetc(in)) != EOF) {
  43. if (i == '\r')
  44. continue;
  45. if (i == '\n')
  46. if (conv_type == CT_UNIX2DOS)
  47. fputc('\r', out);
  48. fputc(i, out);
  49. }
  50. if (fn != NULL) {
  51. if (fclose(in) < 0 || fclose(out) < 0) {
  52. unlink(temp_fn);
  53. bb_perror_nomsg_and_die();
  54. }
  55. xrename(temp_fn, resolved_fn);
  56. free(temp_fn);
  57. free(resolved_fn);
  58. }
  59. }
  60. int dos2unix_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  61. int dos2unix_main(int argc UNUSED_PARAM, char **argv)
  62. {
  63. int o, conv_type;
  64. /* See if we are supposed to be doing dos2unix or unix2dos */
  65. conv_type = CT_UNIX2DOS;
  66. if (applet_name[0] == 'd') {
  67. conv_type = CT_DOS2UNIX;
  68. }
  69. /* -u convert to unix, -d convert to dos */
  70. opt_complementary = "u--d:d--u"; /* mutually exclusive */
  71. o = getopt32(argv, "du");
  72. /* Do the conversion requested by an argument else do the default
  73. * conversion depending on our name. */
  74. if (o)
  75. conv_type = o;
  76. argv += optind;
  77. do {
  78. /* might be convert(NULL) if there is no filename given */
  79. convert(*argv, conv_type);
  80. } while (*argv && *++argv);
  81. return 0;
  82. }