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

后端 未结 13 1247
既然无缘
既然无缘 2020-11-28 17:57

For testing purposes I have to generate a file of a certain size (to test an upload limit).

What is a command to create a file of a certain size on Linux?

13条回答
  •  天涯浪人
    2020-11-28 18:42

    Please, modern is easier, and faster. On Linux, (pick one)

    truncate -s 10G foo
    fallocate -l 5G bar
    

    It needs to be stated that truncate on a file system supporting sparse files will create a sparse file and fallocate will not. A sparse file is one where the allocation units that make up the file are not actually allocated until used. The meta-data for the file will however take up some considerable space but likely no where near the actual size of the file. You should consult resources about sparse files for more information as there are advantages and disadvantages to this type of file. A non-sparse file has its blocks (allocation units) allocated ahead of time which means the space is reserved as far as the file system sees it. Also fallocate nor truncate will not set the contents of the file to a specified value like dd, instead the contents of a file allocated with fallocate or truncate may be any trash value that existed in the allocated units during creation and this behavior may or may not be desired. The dd is the slowest because it actually writes the value or chunk of data to the entire file stream as specified with it's command line options.

    This behavior could potentially be different - depending on file system used and conformance of that file system to any standard or specification. Therefore it is advised that proper research is done to ensure that the appropriate method is used.

提交回复
热议问题