redir-box.c 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <libgen.h>
  4. #include <unistd.h>
  5. #define BUF_SIZE 2096
  6. char buf[BUF_SIZE];
  7. enum { lt, gt, gtgt };
  8. int main(int argc, char **argv) {
  9. int mode, s;
  10. char *flags;
  11. FILE *fin, *fout, *ftmp;
  12. char *name;
  13. if (argc != 2) {
  14. fprintf(stderr, "Error: Invoked with no arguments\n");
  15. return EXIT_FAILURE;
  16. }
  17. name = basename(argv[0]);
  18. if (!strcmp("<", name)) mode = lt;
  19. else if (!strcmp(">", name)) mode = gt;
  20. else if (!strcmp(">>", name)) mode = gtgt;
  21. else {
  22. fprintf(stderr, "Error: Invoked as unknown command [%s]\n", name);
  23. return EXIT_FAILURE;
  24. }
  25. fin = stdin;
  26. fout = stdout;
  27. switch (mode) {
  28. case lt:
  29. flags = "r";
  30. break;
  31. case gt:
  32. flags = "w+";
  33. break;
  34. case gtgt:
  35. flags = "a+";
  36. break;
  37. }
  38. if (!(ftmp = fopen(argv[1], flags))) {
  39. fprintf(stderr, "Could not open file\n");
  40. return EXIT_FAILURE;
  41. }
  42. if (mode == lt)
  43. fin = ftmp;
  44. else
  45. fout = ftmp;
  46. do {
  47. s = fread(buf, 1, BUF_SIZE, fin);
  48. if (fwrite(buf, 1, s, fout) != s) {
  49. fprintf(stderr, "Writing error\n");
  50. }
  51. } while(s != -1 && s != 0);
  52. fclose(fout);
  53. return EXIT_SUCCESS;
  54. }