Saturday, March 27, 2010

Create a file of a given size on linux

Let's say you want to create a file whose size is 1K. You can achieve that by using either of following two commands:

    dd if=/dev/zero of=file bs=1024 count=1

    dd of=file bs=1024 count=0 seek=1

In my test, the generated files are different. The second command generates a file with holes. You can try command stat file. The output in my machine is:

  File: `bigfile'
  Size: 1024            Blocks: 0          IO Block: 4096   regular file

The number of allocated blocks is 0 although size of the file is 1024.
Note: if sparse file is not supported, it may write 1024K zeros to the file.

As a user, you don't need to worry about whether the file is sparse or not. It will grow as needed.