Path: utzoo!mnetor!uunet!husc6!bloom-beacon!oberon!sdcrdcf!hplabs!decwrl!labrea!csli!gandalf From: gandalf@csli.STANFORD.EDU (Juergen Wagner) Newsgroups: comp.unix.questions Subject: Re: checking disk space from c program Message-ID: <3431@csli.STANFORD.EDU> Date: 10 Apr 88 01:09:06 GMT References: <398@wpg.UUCP> Reply-To: gandalf@csli.stanford.edu (Juergen Wagner) Organization: Center for the Study of Language and Information, Stanford U. Lines: 94 Yes, there is a way to find out the space available on the file system a particular file resides on. The only problem is that you have to setuid to root to be able to read the disk device. Normal users will have to use df. Here comes a small program which does the job (usage: "d " tells you the free space on the file system of ). Juergen "Gandalf" Wagner, gandalf@csli.stanford.edu Center for the Study of Language and Information (CSLI), Stanford CA /* ** Unpack this into d.c ** $Compile: cc -g -o d d.c */ # include # include # include # include # include # include # include union { struct fs iu_fs; char dummy[SBSIZE]; } sb; # define sblock sb.iu_fs static char *getfs(file,dev) char *file; int dev; { struct stat s; struct fstab *fs; if (dev > 0) { setfsent(); while (fs = getfsent()) { if (stat(fs->fs_spec, &s)) continue; if (s.st_rdev == dev) { endfsent(); return(fs->fs_spec); } } } else return(file); } main(argc, argv) int argc; char **argv; { char *file = argv[1]; int f; int totalblks, free, used, availblks, avail; int freeblks; struct stat s; if (stat(file, &s)) { perror(file); exit(1); } if ((s.st_mode & S_IFMT) != S_IFBLK) file = getfs(file,s.st_dev); if (stat(file, &s)) { perror(file); exit(1); } if ((s.st_mode & S_IFMT) != S_IFBLK) { printf("%s is not a block-oriented device", file); exit(1); } f = open(file, O_RDONLY); if (f < 0) { perror(file); exit(1); } lseek(f, (long) (SBLOCK * DEV_BSIZE), 0); read(f, &sblock, SBSIZE); totalblks = sblock.fs_dsize; free = sblock.fs_cstotal.cs_nbfree * sblock.fs_frag + sblock.fs_cstotal.cs_nffree; used = totalblks - free; availblks = totalblks * (100 - sblock.fs_minfree) / 100; avail = availblks > used ? availblks - used : 0; freeblks = avail * sblock.fs_fsize / 1024; printf("free of %s: %d\n", file, freeblks); exit(0); } -- Juergen "Gandalf" Wagner, gandalf@csli.stanford.edu Center for the Study of Language and Information (CSLI), Stanford CA