stat.c 1.7 KB

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