Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

112 Files and Directories Chapter 4


$wc -c core
8483248 core

Thewc( 1 )command with the-coption counts the number of characters (bytes) in the file.

If we make a copy of this file, using a utility such ascat( 1 ),all these holes are
written out as actual data bytes of 0:
$cat core > core.copy
$ls -l core*
-rw-r--r-- 1 sar 8483248 Nov 18 12:18 core
-rw-rw-r-- 1 sar 8483248 Nov 18 12:27 core.copy
$du -s core*
272 core
16592 core.copy
Here, the actual number of bytes used by the new file is 8,495,104( 512 ×16,592).The
difference between this size and the size reported bylsis caused by the number of
blocks used by the file system to hold pointers to the actual data blocks.
Interested readers should refer to Section 4.2 of Bach[ 1986 ],Sections 7.2 and 7.3 of
McKusick et al.[ 1996 ](or Sections 8.2 and 8.3 in McKusick and Neville-Neil[ 2005 ]),
Section 15.2 of McDougall and Mauro[ 2007 ],and Chapter 12 in Singh [ 2006 ] for
additional details on the physical layout of files.

4.13 FileTr uncation


Sometimes we would like to truncate a file by chopping offdata at the end of the file.
Emptying a file, which we can do with theO_TRUNCflag toopen, is a special case of
truncation.
#include <unistd.h>
int truncate(const char *pathname,off_tlength);
int ftruncate(intfd,off_tlength);
Both return: 0 if OK,−1 on error
These two functions truncate an existing file tolengthbytes. If the previous size of the
file was greater thanlength,the data beyondlengthis no longer accessible. Otherwise, if
the previous size was less thanlength,the file size will increase and the data between
the old end of file and the new end of file will read as 0 (i.e., a hole is probably created
in the file).

BSD releases prior to 4.4BSD could only make a file smaller withtruncate.
Solaris also includes an extension tofcntl(F_FREESP)that allows us to free any part of a
file, not just a chunk at the end of the file.

We useftruncatein the program shown in Figure13.6 when we need to empty a
file after obtaining a lock on the file.
Free download pdf