Wednesday, March 9, 2011

Calculating Free Bytes (Wasted ) On Disk-Data Structures

Calculating Wasted Bytes On Disk

When a file gets stored on the disk, at a time DOS allocates one cluster for it. A cluster is nothing but a group of sectors. However, since all file sizes cannot be expected to be a multiple of 512 bytes, when a file gets stored often part of the cluster remains unoccupied. This space goes waste unless the file size grows to occupy these wasted bytes. The
following program finds out how much space is wasted for all files in all the directories of the current drive.
#include 
#include 
#include 
#include 
#include 
unsigned bytes_per_cluster ;
unsigned long wasted_bytes ;
unsigned long num_files = 0 ;
main( )
{
int ptr = 0, flag = 0, first = 0 ;
struct ffblk f[50] ;
struct dfree free ;
/* get cluster information and calculate bytes per cluster */
getdfree ( 0, &free ) ;
bytes_per_cluster = free.df_bsec * free.df_sclus ;
chdir ( "\\" ) ;
/* check out files in root directory first */
cal_waste( ) ;
/* loop until all directories scanned */
while ( ptr != -1 )
{
/* should I do a findfirst or a findnext? */
if ( first == 0 )
flag = findfirst ( "*.*", &f[ptr], FA_DIREC ) ;
else
flag = findnext ( &f[ptr] ) ;
while ( flag == 0 )
{
/* make sure its a directory and skip over . & .. entries */
if ( f[ptr].ff_attrib == FA_DIREC && f[ptr].ff_name[0] != '.' )
{
flag = chdir ( f[ptr].ff_name ) ; /* try changing directories */
if ( flag == 0 ) /* did change dir work? */
{
cal_waste( ) ;
first = 0 ; /* set for findfirst on next pass */
break ;
}
}
flag = findnext ( &f[ptr] ) ; /* search for more dirs */
}
if ( flag != 0 || ptr == 49 ) /* didn't find any more dirs */
{
ptr-- ;
chdir ( ".." ) ; /* go back one level */
first = 1 ; /* set to findnext on next pass */
}
else
ptr++ ;
}
printf ( "There are %lu bytes wasted in %lu files.\n", wasted_bytes,
num_files ) ;
}
cal_waste( )
{
int flag = 0 ;
long full_cluster ;
struct ffblk ff ;
/* look for all file types */
flag = findfirst ( "*.*", &ff, FA_RDONLY | FA_HIDDEN | FA_SYSTEM | FA_ARCH
) ;
while ( flag == 0 )
{
num_files++ ;
full_cluster = ff.ff_fsize / bytes_per_cluster * bytes_per_cluster ;
wasted_bytes += bytes_per_cluster - ( ff.ff_fsize - full_cluster ) ;
flag = findnext ( &ff ) ;
}
}

No comments:

Blog List