stat.c 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /* vim: ts=4 sw=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-2018 K. Lange
  5. *
  6. * stat
  7. *
  8. * Display file status.
  9. */
  10. #include <stdio.h>
  11. #include <stdint.h>
  12. #include <string.h>
  13. #include <unistd.h>
  14. #include <sys/stat.h>
  15. #include <sys/time.h>
  16. static void show_usage(int argc, char * argv[]) {
  17. printf(
  18. "stat - display file status\n"
  19. "\n"
  20. "usage: %s [-Lq] PATH\n"
  21. "\n"
  22. " -L \033[3mdereference symlinks\033[0m\n"
  23. " -q \033[3mdon't print anything, just return 0 if file exists\033[0m\n"
  24. " -? \033[3mshow this help text\033[0m\n"
  25. "\n", argv[0]);
  26. }
  27. int main(int argc, char ** argv) {
  28. int dereference = 0, quiet = 0;
  29. char * file;
  30. int opt;
  31. while ((opt = getopt(argc, argv, "?Lq")) != -1) {
  32. switch (opt) {
  33. case 'L':
  34. dereference = 1;
  35. break;
  36. case 'q':
  37. quiet = 1;
  38. break;
  39. case '?':
  40. show_usage(argc,argv);
  41. return 1;
  42. }
  43. }
  44. if (optind >= argc) {
  45. show_usage(argc, argv);
  46. return 1;
  47. }
  48. file = argv[optind];
  49. struct stat _stat;
  50. if (dereference) {
  51. if (stat(file, &_stat) < 0) return 1;
  52. } else {
  53. if (lstat(file, &_stat) < 0) return 1;
  54. }
  55. if (quiet) return 0;
  56. printf("0x%x bytes\n", (unsigned int)_stat.st_size);
  57. if (S_ISDIR(_stat.st_mode)) {
  58. printf("Is a directory.\n");
  59. } else if (S_ISFIFO(_stat.st_mode)) {
  60. printf("Is a pipe.\n");
  61. } else if (S_ISLNK(_stat.st_mode)) {
  62. printf("Is a symlink.\n");
  63. } else if (_stat.st_mode & 0111) {
  64. printf("Is executable.\n");
  65. }
  66. struct stat * f = &_stat;
  67. printf("st_dev 0x%x %d\n", (unsigned int)f->st_dev , (unsigned int)sizeof(f->st_dev ));
  68. printf("st_ino 0x%x %d\n", (unsigned int)f->st_ino , (unsigned int)sizeof(f->st_ino ));
  69. printf("st_mode 0x%x %d\n", (unsigned int)f->st_mode , (unsigned int)sizeof(f->st_mode ));
  70. printf("st_nlink 0x%x %d\n", (unsigned int)f->st_nlink , (unsigned int)sizeof(f->st_nlink ));
  71. printf("st_uid 0x%x %d\n", (unsigned int)f->st_uid , (unsigned int)sizeof(f->st_uid ));
  72. printf("st_gid 0x%x %d\n", (unsigned int)f->st_gid , (unsigned int)sizeof(f->st_gid ));
  73. printf("st_rdev 0x%x %d\n", (unsigned int)f->st_rdev , (unsigned int)sizeof(f->st_rdev ));
  74. printf("st_size 0x%x %d\n", (unsigned int)f->st_size , (unsigned int)sizeof(f->st_size ));
  75. printf("0x%x\n", (unsigned int)((uint32_t *)f)[0]);
  76. return 0;
  77. }