1 /* Convert file size to number of blocks on System V-like machines.
2 
3    Copyright (C) 1990, 1997-1999, 2004-2006, 2009-2021 Free Software
4    Foundation, Inc.
5 
6    This program is free software: you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10 
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15 
16    You should have received a copy of the GNU General Public License
17    along with this program.  If not, see <https://www.gnu.org/licenses/>.  */
18 
19 /* Written by Brian L. Matthews, blm@6sceng.UUCP. */
20 
21 #include <config.h>
22 
23 #include <sys/types.h>
24 
25 #if HAVE_SYS_PARAM_H
26 # include <sys/param.h>
27 #endif
28 
29 #if !HAVE_STRUCT_STAT_ST_BLOCKS && !defined _POSIX_SOURCE && defined BSIZE
30 
31 # include <unistd.h>
32 
33 # ifndef NINDIR
34 
35 #  if defined __DJGPP__
36 typedef long daddr_t; /* for disk address */
37 #  endif
38 
39 /* Some SysV's, like Irix, seem to lack this.  Hope it's correct. */
40 /* Number of inode pointers per indirect block. */
41 #  define NINDIR (BSIZE / sizeof (daddr_t))
42 # endif /* !NINDIR */
43 
44 /* Number of direct block addresses in an inode. */
45 # define NDIR   10
46 
47 /* Return the number of 512-byte blocks in a file of SIZE bytes. */
48 
49 off_t
st_blocks(off_t size)50 st_blocks (off_t size)
51 {
52   off_t datablks = size / 512 + (size % 512 != 0);
53   off_t indrblks = 0;
54 
55   if (datablks > NDIR)
56     {
57       indrblks = (datablks - NDIR - 1) / NINDIR + 1;
58 
59       if (datablks > NDIR + NINDIR)
60         {
61           indrblks += (datablks - NDIR - NINDIR - 1) / (NINDIR * NINDIR) + 1;
62 
63           if (datablks > NDIR + NINDIR + NINDIR * NINDIR)
64             indrblks++;
65         }
66     }
67 
68   return datablks + indrblks;
69 }
70 #else
71 /* This declaration is solely to ensure that after preprocessing
72    this file is never empty.  */
73 typedef int textutils_fileblocks_unused;
74 #endif
75