lazybox.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. #include <unistd.h>
  2. #include <dirent.h>
  3. #include <stdarg.h>
  4. #include <stdint.h>
  5. #include <stdio.h>
  6. #include <string.h>
  7. struct applet {
  8. const char* name;
  9. int (*func)(const char** args);
  10. };
  11. int lazybox_version(void)
  12. {
  13. printf("lazybox by greatbridf\n");
  14. return 0;
  15. }
  16. int pwd(const char** _)
  17. {
  18. (void)_;
  19. char buf[256];
  20. if (getcwd(buf, sizeof(buf)) == 0) {
  21. printf("cannot get cwd\n");
  22. return -1;
  23. }
  24. puts(buf);
  25. return 0;
  26. }
  27. int ls(const char** args)
  28. {
  29. const char* path = args[0];
  30. DIR* dir = NULL;
  31. if (path == NULL) {
  32. char buf[256];
  33. if (getcwd(buf, sizeof(buf)) == 0)
  34. return -1;
  35. dir = opendir(buf);
  36. } else {
  37. dir = opendir(args[0]);
  38. }
  39. if (!dir)
  40. return -1;
  41. struct dirent* dp = NULL;
  42. while ((dp = readdir(dir)) != NULL) {
  43. printf("%s ", dp->d_name);
  44. }
  45. printf("\n");
  46. return 0;
  47. }
  48. struct applet applets[] = {
  49. {
  50. "lazybox",
  51. NULL,
  52. },
  53. {
  54. "pwd",
  55. pwd,
  56. },
  57. {
  58. "ls",
  59. ls,
  60. }
  61. };
  62. static inline int tolower(int c)
  63. {
  64. if (c >= 'A' && c <= 'Z')
  65. return c - 'A' + 'a';
  66. return c;
  67. }
  68. int strcmpi(const char* a, const char* b)
  69. {
  70. int ret = 0;
  71. while (*a && *b) {
  72. if (tolower(*a) != tolower(*b)) {
  73. ret = 1;
  74. break;
  75. }
  76. ++a, ++b;
  77. }
  78. if ((*a && !*b) || (*b && !*a)) {
  79. ret = 1;
  80. }
  81. return ret;
  82. }
  83. const char* find_file_name(const char* path)
  84. {
  85. const char* last = path + strlen(path);
  86. for (; last != path; --last) {
  87. if (*last == '/') {
  88. ++last;
  89. break;
  90. }
  91. }
  92. return last == path ? path : last + 1;
  93. }
  94. int parse_applet(const char* name)
  95. {
  96. if (!name)
  97. return -1;
  98. for (size_t i = 0; i < (sizeof(applets) / sizeof(struct applet)); ++i) {
  99. if (strcmpi(applets[i].name, name) == 0) {
  100. return i;
  101. }
  102. }
  103. return -1;
  104. }
  105. int main(int argc, const char** argv)
  106. {
  107. if (argc == 0)
  108. return lazybox_version();
  109. const char* name = find_file_name(*argv);
  110. int type = parse_applet(find_file_name(*argv));
  111. if (type < 0) {
  112. printf("applet not found: %s\n", name);
  113. return -1;
  114. }
  115. if (type == 0)
  116. return main(argc - 1, argv + 1);
  117. return applets[type].func(argv + 1);
  118. }