Reputation: 665
I need a function which will create a file with fixed size in linux. Function like truncate
or fopen,fseek,fclose
, is not a solution because, they will fill opened file with zeros, but it is not necessary and I have no time for this. So is there some function, which will only open a file with fixed length and not fill buffer?
Thanks in advance.
Upvotes: 1
Views: 1554
Reputation: 182639
The system call truncate(2)
doesn't fill the file with zeros. It simply advances the file's reported size and leaves holes in it.
When you read from it, you do get zeros, but that's just a convenience of the OS.
The truncate() and ftruncate() functions cause the regular file named by path or referenced by fd to be truncated to a size of precisely length bytes.
If the file previously was shorter, it is extended, and the extended part reads as null bytes ('\0').
About holes (from TLPI):
The existence of holes means that a file’s nominal size may be larger than the amount of disk storage it utilizes (in some cases, considerably larger).
Filesystems and holes:
Rather than allocate blocks of null bytes for the holes in a file, the file system can just mark (with the value 0) appropriate pointers in the i-node and in the indirect pointer blocks to indicate that they don't refer to actual disk blocks.
As Per Johansson notes, this is dependent of the filesystem.
Most native UNIX file systems support the concept of file holes, but many nonnative file systems (e.g., Microsoft’s VFAT) do not. On a file system that doesn’t support holes, explicit null bytes are written to the file.
Upvotes: 10