mkdir.c 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <string.h>
  4. #include <errno.h>
  5. #include <limits.h>
  6. #include <sys/stat.h>
  7. static int usage()
  8. {
  9. fprintf(stderr,"mkdir [OPTION] <target>\n");
  10. fprintf(stderr," --help display usage and exit\n");
  11. fprintf(stderr," -p, --parents create parent directories as needed\n");
  12. return -1;
  13. }
  14. int main(int argc, char *argv[])
  15. {
  16. int ret;
  17. if(argc < 2 || strcmp(argv[1], "--help") == 0) {
  18. return usage();
  19. }
  20. int recursive = (strcmp(argv[1], "-p") == 0 ||
  21. strcmp(argv[1], "--parents") == 0) ? 1 : 0;
  22. if(recursive && argc < 3) {
  23. // -p specified without a path
  24. return usage();
  25. }
  26. if(recursive) {
  27. argc--;
  28. argv++;
  29. }
  30. char currpath[PATH_MAX], *pathpiece;
  31. struct stat st;
  32. while(argc > 1) {
  33. argc--;
  34. argv++;
  35. if(recursive) {
  36. // reset path
  37. strcpy(currpath, "");
  38. // create the pieces of the path along the way
  39. pathpiece = strtok(argv[0], "/");
  40. if(argv[0][0] == '/') {
  41. // prepend / if needed
  42. strcat(currpath, "/");
  43. }
  44. while(pathpiece != NULL) {
  45. if(strlen(currpath) + strlen(pathpiece) + 2/*NUL and slash*/ > PATH_MAX) {
  46. fprintf(stderr, "Invalid path specified: too long\n");
  47. return 1;
  48. }
  49. strcat(currpath, pathpiece);
  50. strcat(currpath, "/");
  51. if(stat(currpath, &st) != 0) {
  52. ret = mkdir(currpath, 0777);
  53. if(ret < 0) {
  54. fprintf(stderr, "mkdir failed for %s, %s\n", currpath, strerror(errno));
  55. return ret;
  56. }
  57. }
  58. pathpiece = strtok(NULL, "/");
  59. }
  60. } else {
  61. ret = mkdir(argv[0], 0777);
  62. if(ret < 0) {
  63. fprintf(stderr, "mkdir failed for %s, %s\n", argv[0], strerror(errno));
  64. return ret;
  65. }
  66. }
  67. }
  68. return 0;
  69. }