checking disk space from c program

Juergen Wagner gandalf at csli.STANFORD.EDU
Sun Apr 10 11:09:06 AEST 1988


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 <file>" tells you
the free space on the file system of <file>).

Juergen "Gandalf" Wagner,		   gandalf at 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 <stdio.h>
# include <sys/param.h>
# include <sys/stat.h>
# include <sys/ioctl.h>
# include <sys/file.h>
# include <ufs/fs.h>
# include <fstab.h>

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 at csli.stanford.edu
Center for the Study of Language and Information (CSLI), Stanford CA



More information about the Comp.unix.questions mailing list