module_03.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <errno.h>
  5. #include <sys/stat.h>
  6. #include <sys/sysmacros.h>
  7. #include <unistd.h>
  8. //#include "log.h"
  9. #define BOLD_GRAY "\033[1;90m"
  10. #define RED "\033[0;31m"
  11. #define WHITE "\033[0;37m"
  12. #define RESET "\033[0m"
  13. int module_03_run(const char *filename) {
  14. char log_msg[1024];
  15. struct stat st;
  16. if (stat(filename, &st) != 0) {
  17. snprintf(log_msg, sizeof(log_msg), BOLD_GRAY " Library libstat: " RED "File type not recognized: %s" RESET, strerror(errno));
  18. printf("%s\n", log_msg);
  19. // log_message(log_msg);
  20. return 1;
  21. }
  22. const char *type;
  23. char extra_info[512] = "";
  24. if (S_ISREG(st.st_mode)) {
  25. type = "regular file";
  26. } else if (S_ISDIR(st.st_mode)) {
  27. type = "directory";
  28. } else if (S_ISCHR(st.st_mode)) {
  29. type = "character device";
  30. snprintf(extra_info, sizeof(extra_info), ", Major: %d, Minor: %d",
  31. major(st.st_rdev), minor(st.st_rdev));
  32. } else if (S_ISBLK(st.st_mode)) {
  33. type = "block device";
  34. snprintf(extra_info, sizeof(extra_info), ", Major: %d, Minor: %d",
  35. major(st.st_rdev), minor(st.st_rdev));
  36. } else if (S_ISFIFO(st.st_mode)) {
  37. type = "FIFO (named pipe)";
  38. } else if (S_ISSOCK(st.st_mode)) {
  39. type = "socket";
  40. } else if (S_ISLNK(st.st_mode)) {
  41. type = "symbolic link";
  42. char link_target[256];
  43. ssize_t len = readlink(filename, link_target, sizeof(link_target) - 1);
  44. if (len != -1) {
  45. link_target[len] = '\0';
  46. snprintf(extra_info, sizeof(extra_info), ", Points to: %s", link_target);
  47. } else {
  48. snprintf(extra_info, sizeof(extra_info), ", Error reading link: %s", strerror(errno));
  49. }
  50. } else {
  51. type = "unknown";
  52. }
  53. if (strncmp(filename, "/proc/", 6) == 0) {
  54. type = "procfs pseudo-file";
  55. } else if (strncmp(filename, "/sys/", 5) == 0) {
  56. type = "sysfs pseudo-file";
  57. }
  58. snprintf(log_msg, sizeof(log_msg), BOLD_GRAY " Library libstat: " WHITE "Size: %ld bytes, Permissions: %o, Type: %s%s" RESET,
  59. (long)st.st_size, st.st_mode & 0777, type, extra_info);
  60. printf("%s\n", log_msg);
  61. // log_message(log_msg);
  62. return 0;
  63. }