cp.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /* vim: tabstop=4 shiftwidth=4 noexpandtab
  2. * This file is part of ToaruOS and is released under the terms
  3. * of the NCSA / University of Illinois License - see LICENSE.md
  4. * Copyright (C) 2013 K. Lange
  5. * Copyright (C) 2013 Tyler Bindon
  6. *
  7. * cp - Copy files
  8. *
  9. * This is an incomplete implementation of `cp`. A more complete
  10. * version of recursive directory copying can be found in the
  11. * `migrate` sources, and should probably be imported here.
  12. */
  13. #include <stdlib.h>
  14. #include <string.h>
  15. #include <sys/stat.h>
  16. #include <stdio.h>
  17. #define CHUNK_SIZE 4096
  18. int main(int argc, char ** argv) {
  19. FILE * fd;
  20. FILE * fout;
  21. if (argc < 3) {
  22. fprintf(stderr, "usage: %s [source] [destination]\n", argv[0]);
  23. return 1;
  24. }
  25. fd = fopen(argv[1], "r");
  26. if (!fd) {
  27. fprintf(stderr, "%s: %s: no such file or directory\n", argv[0], argv[1]);
  28. return 1;
  29. }
  30. struct stat statbuf;
  31. stat(argv[2], &statbuf);
  32. if (S_ISDIR(statbuf.st_mode)) {
  33. char *filename = strrchr(argv[1], '/');
  34. if (!filename) {
  35. filename = argv[1];
  36. }
  37. char *target_path = malloc((strlen(argv[2]) + strlen(filename) + 2) * sizeof(char));
  38. sprintf(target_path, "%s/%s", argv[2], filename );
  39. fout = fopen( target_path, "w" );
  40. free(target_path);
  41. } else {
  42. fout = fopen( argv[2], "w" );
  43. }
  44. size_t length;
  45. fseek(fd, 0, SEEK_END);
  46. length = ftell(fd);
  47. fseek(fd, 0, SEEK_SET);
  48. char buf[CHUNK_SIZE];
  49. while (length > CHUNK_SIZE) {
  50. fread( buf, 1, CHUNK_SIZE, fd);
  51. fwrite(buf, 1, CHUNK_SIZE, fout);
  52. length -= CHUNK_SIZE;
  53. }
  54. if (length > 0) {
  55. fread( buf, 1, length, fd);
  56. fwrite(buf, 1, length, fout);
  57. }
  58. fclose(fd);
  59. fclose(fout);
  60. return 0;
  61. }