GNU file utilities
[gnulib.git] / lib / fileblocks.c
1 /* Convert file size to number of blocks on System V-like machines.
2    Copyright (C) 1990 Free Software Foundation, Inc.
3
4    This program is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 2, or (at your option)
7    any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program; if not, write to the Free Software
16    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
17
18 /* Written by Brian L. Matthews, blm@6sceng.UUCP. */
19 \f
20 #ifdef HAVE_CONFIG_H
21 #if defined (CONFIG_BROKETS)
22 /* We use <config.h> instead of "config.h" so that a compilation
23    using -I. -I$srcdir will use ./config.h rather than $srcdir/config.h
24    (which it would do because it found this file in $srcdir).  */
25 #include <config.h>
26 #else
27 #include "config.h"
28 #endif
29 #endif
30
31 #if !defined (HAVE_ST_BLOCKS) && !defined(_POSIX_SOURCE)
32 #include <sys/types.h>
33 #include <sys/param.h>
34
35 #ifndef NINDIR
36 /* Some SysV's, like Irix, seem to lack these.  Hope they're correct. */
37 /* Size of a indirect block, in bytes. */
38 #ifndef BSIZE
39 #define BSIZE 1024
40 #endif
41
42 /* Number of inode pointers per indirect block. */
43 #define NINDIR (BSIZE/sizeof(daddr_t))
44 #endif /* !NINDIR */
45
46 /* Number of direct block addresses in an inode. */
47 #define NDIR    10
48
49 /* Return the number of 512-byte blocks in a file of SIZE bytes. */
50
51 long
52 st_blocks (size)
53      long size;
54 {
55   long datablks = (size + 512 - 1) / 512;
56   long indrblks = 0;
57
58   if (datablks > NDIR)
59     {
60       indrblks = (datablks - NDIR - 1) / NINDIR + 1;
61
62       if (datablks > NDIR + NINDIR)
63         {
64           indrblks += (datablks - NDIR - NINDIR - 1) / (NINDIR * NINDIR) + 1;
65
66           if (datablks > NDIR + NINDIR + NINDIR * NINDIR)
67             indrblks++;
68         }
69     }
70
71   return datablks + indrblks;
72 }
73 #endif