stat.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <fcntl.h>
  4. #include <sys/stat.h>
  5. #include <unistd.h>
  6. #include <stdlib.h>
  7. static void print_struct_stat(char *msg, struct stat *s)
  8. {
  9. printf("%s\n", msg);
  10. /* The casts are because glibc thinks it's cool */
  11. printf("device : 0x%llx\n",(long long)s->st_dev);
  12. printf("inode : %lld\n", (long long)s->st_ino);
  13. printf("mode : 0x%llx\n",(long long)s->st_mode);
  14. printf("nlink : %lld\n", (long long)s->st_nlink);
  15. printf("uid : %lld\n", (long long)s->st_uid);
  16. printf("gid : %lld\n", (long long)s->st_gid);
  17. printf("rdev : 0x%llx\n",(long long)s->st_rdev);
  18. printf("size : %lld\n", (long long)s->st_size);
  19. printf("blksize : %lld\n", (long long)s->st_blksize);
  20. printf("blocks : %lld\n", (long long)s->st_blocks);
  21. printf("atime : %lld\n", (long long)s->st_atime);
  22. printf("mtime : %lld\n", (long long)s->st_mtime);
  23. printf("ctime : %lld\n", (long long)s->st_ctime);
  24. }
  25. int main(int argc,char **argv)
  26. {
  27. int fd, ret;
  28. char *file;
  29. struct stat s;
  30. if (argc < 2) {
  31. fprintf(stderr, "Usage: stat FILE\n");
  32. exit(1);
  33. }
  34. file = argv[1];
  35. memset(&s, 0, sizeof(struct stat));
  36. ret = stat(file, &s);
  37. if(ret<0){
  38. perror("stat");
  39. exit(1);
  40. }
  41. print_struct_stat("\nTesting stat:", &s);
  42. memset(&s, 0, sizeof(struct stat));
  43. ret = lstat(file, &s);
  44. if(ret<0){
  45. perror("lstat");
  46. exit(1);
  47. }
  48. print_struct_stat("\nTesting lstat:", &s);
  49. fd = open(file, O_RDONLY);
  50. if(fd<0){
  51. perror("open");
  52. exit(1);
  53. }
  54. memset(&s, 0, sizeof(struct stat));
  55. ret = fstat(fd,&s);
  56. if(ret<0){
  57. perror("fstat");
  58. exit(1);
  59. }
  60. print_struct_stat("\nTesting fstat:", &s);
  61. exit(0);
  62. }