By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,986 Members | 1,960 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,986 IT Pros & Developers. It's quick & easy.

get disk usage

P: 2
Hi:

Somebody knows how I can obtain disk space usage and the space that left in disk.
Sep 20 '06 #1
Share this Question
Share on Google+
2 Replies


100+
P: 144
On a POSIX system you would use the file system statistics data type and function calls. These are defined in <sys/statvfs.h>.

Here is what the data structure and funtion prototypes should look like in <sys/statvfs.h>

Expand|Select|Wrap|Line Numbers
  1. struct statvfs {
    unsigned long  f_bsize;    /* file system block size */
  2. unsigned long  f_frsize;   /* fragment size */
  3. fsblkcnt_t     f_blocks;   /* size of fs in f_frsize units */
  4. fsblkcnt_t     f_bfree;    /* # free blocks */
  5. fsblkcnt_t     f_bavail;   /* # free blocks for non-root */
  6. fsfilcnt_t     f_files;    /* # inodes */
  7. fsfilcnt_t     f_ffree;    /* # free inodes */
  8. fsfilcnt_t     f_favail;   /* # free inodes for non-root */
  9. unsigned long  f_fsid;     /* file system ID */
  10. unsigned long  f_flag;     /* mount flags */
  11. unsigned long  f_namemax;  /* maximum filename length */};
  12.  
  13. /* These functions return 0 on success and -1 on failure */
  14.  
  15. int statvfs(const char *filename, struct statvfs buf);
  16. int fstatvfs(int fd, struct statvfs buf);
  17.  
This sample code outputs the disk usage and free space in bytes.

Expand|Select|Wrap|Line Numbers
  1. include <sys/statvfs.h>
  2.  
  3. ...
  4.  
  5. /* Any file on the filesystem in question */
  6. char *filename = "/home/tyreld/somefile.txt";
  7.  
  8. struct statvfs buf;
  9. if (!statvfs(filename, &buf)) {
    unsigned long blksize, blocks, freeblks, disk_size, used, free;
  10.  
  11. blksize = buf.f_bsize;
  12. blocks = buf.f_blocks;
  13. freeblks = buf.f_bfree;
  14.  
  15. disk_size = blocks * blksize;
  16. free = freeblks * blksize;
  17. used = disk_size - free;
  18.  
  19. printf("Disk usage : %lu \t Free space %lu\n", used, free);} else {
    printf("Couldn't get file system statistics\n");
    }
  20.  
  21.  
Sep 20 '06 #2

P: 1
Thanks tyreld

Good post..Aftr searching long time got this post..
I have used it as part of my code.
Jan 31 '12 #3

Post your reply

Sign in to post your reply or Sign up for a free account.