他们都可以根据我的测试改变文件大小。 为什么他们都可以将文件更改为更大或更短? fallocate 和 ftruncate 有什么区别?
最佳答案
ftruncate
是一个简单的单一用途函数。 Per the POSIX documentation ,它只是将文件设置为请求的长度:
If
fildes
refers to a regular file, theftruncate()
function shall cause the size of the file to be truncated tolength
. ...
ftruncate()
也是一个标准的 POSIX 函数并且是可移植的。请注意,POSIX 不指定操作系统如何设置文件长度,例如设置为任意长度的文件是否为a sparse file。 .
fallocate()
is a Linux-specific function它以非常具体的方式做了更多:
Allocating disk space
The default operation (i.e., mode is zero) of fallocate() allocates the disk space within the range specified by
offset
andlen
. The file size (as reported bystat(2)
) will be changed ifoffset+len
is greater than the file size. Any subregion within the range specified by offset and len that did not contain data before the call will be initialized to zero. This default behavior closely resembles the behavior of theposix_fallocate(3)
library function, and is intended as a method of optimally implementing that function....
Deallocating file space
Specifying the
FALLOC_FL_PUNCH_HOLE
flag (available since Linux 2.6.38) in mode deallocates space (i.e., creates a hole) in the byte range starting atoffset
and continuing forlen
bytes. Within the specified range, partial filesystem blocks are zeroed, and whole filesystem blocks are removed from the file. After a successful call, subsequent reads from this range will return zeroes....
Collapsing file space
Specifying the
FALLOC_FL_COLLAPSE_RANGE
flag (available since Linux 3.15) in mode removes a byte range from a file, without leaving a hole. The byte range to be collapsed starts atoffset
and continues forlen
bytes. At the completion of the operation, the contents of the file starting at the locationoffset+len
will be appended at the location offset, and the file will belen
bytes smaller....
Zeroing file space
Specifying the
FALLOC_FL_ZERO_RANGE
flag (available since Linux 3.15) in mode zeroes space in the byte range starting atoffset
and continuing forlen
bytes. Within the specified range, blocks are preallocated for the regions that span the holes in the file. After a successful call, subsequent reads from this range will return zeroes....
Increasing file space
Specifying the
FALLOC_FL_INSERT_RANGE
flag (available since Linux 4.1) in mode increases the file space by inserting a hole within the file size without overwriting any existing data. The hole will start atoffset
and continue forlen
bytes. When inserting the hole inside file, the contents of the file starting atoffset
will be shifted upward (i.e., to a higher file offset) bylen
bytes. Inserting a hole inside a file increases the file size bylen
bytes....
关于c - fallocate 和 ftruncate 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49360932/