How to create a file with ANY given size in Linux?

后端 未结 4 1460
Happy的楠姐
Happy的楠姐 2021-01-04 18:45

I have read this question: How to create a file with a given size in Linux?

But I havent got answer to my question.

I want to create a file of 372.07 MB,

相关标签:
4条回答
  • 2021-01-04 19:24

    Swap count and bs. bs bytes will be in memory, so it can't be that big.

    0 讨论(0)
  • 2021-01-04 19:30

    Sparse file

    dd of=output.dat bs=1 seek=390143672 count=0
    

    This has the added benefit of creating the file sparse if the underlying filesystem supports that. This means, no space is wasted if some of the pages (_blocks) ever get written to and the file creation is extremely quick.


    Non-sparse (opaque) file:

    Edit since people have, rightly pointed out that sparse files have characteristics that could be disadvantageous in some scenarios, here is the sweet point:

    You could use fallocate (in Debian present due to util-linux) instead:

    fallocate -l 390143672 output.dat
    

    This still has the benefit of not needing to actually write the blocks, so it is pretty much as quick as creating the sparse file, but it is not sparse. Best Of Both Worlds.

    0 讨论(0)
  • 2021-01-04 19:31

    truncate - shrink or extend the size of a file to the specified size

    The following example truncates putty.log from 298 bytes to 235 bytes.

    root@ubuntu:~# ls -l putty.log 
    -rw-r--r-- 1 root root 298 2013-10-11 03:01 putty.log
    root@ubuntu:~# truncate putty.log -s 235
    root@ubuntu:~# ls -l putty.log 
    -rw-r--r-- 1 root root 235 2013-10-14 19:07 putty.log
    
    0 讨论(0)
  • 2021-01-04 19:43

    Change your parameters:

    dd if=/dev/zero of=output.dat bs=1 count=390143672
    

    otherwise dd tries to create a 370MB buffer in memory.

    If you want to do it more efficiently, write the 372MB part first with large-ish blocks (say 1M), then write the tail part with 1 byte blocks by using the seek option to go to the end of the file first.

    Ex:

    dd if=/dev/zero of=./output.dat bs=1M count=1
    dd if=/dev/zero of=./output.dat seek=1M bs=1 count=42
    
    0 讨论(0)
提交回复
热议问题