truncate, ftruncate - truncate a file to a specified length
Sometimes we would like to truncate a file by chopping off(砍去) data at the end of the file.
Emptying a file, which we can do with the O_TRUNC
flag to open
, is a special case of truncation
.
函数原型如下:
#include <unistd.h>
#include <sys/types.h>
int truncate(const char *path, off_t length);
int ftruncate(int fd, off_t length);
//Both Returns: 0 if OK, -1 on error
将会将文件截断到length
字节。如果length
大于先前的长度,则两长度之间的数据无法访问。如果先前长度小于length
,则会将文件尺寸扩大到length
,在old end 和 new end之间的数据在read
时作为0.
We use ftruncate
in the program shown in Figure 13.6 when we need to empty a file after obtaining a lock on the file.