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

后端 未结 13 1089
既然无缘
既然无缘 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:17

    On OSX (and Solaris, apparently), the mkfile command is available as well:

    mkfile 10g big_file
    

    This makes a 10 GB file named "big_file". Found this approach here.

    0 讨论(0)
  • 2020-11-28 18:17

    Use this command:

    dd if=$INPUT-FILE of=$OUTPUT-FILE bs=$BLOCK-SIZE count=$NUM-BLOCKS
    

    To create a big (empty) file, set $INPUT-FILE=/dev/zero.
    Total size of the file will be $BLOCK-SIZE * $NUM-BLOCKS.
    New file created will be $OUTPUT-FILE.

    0 讨论(0)
  • 2020-11-28 18:19

    Just to follow up Tom's post, you can use dd to create sparse files as well:

    dd if=/dev/zero of=the_file bs=1 count=0 seek=12345
    

    This will create a file with a "hole" in it on most unixes - the data won't actually be written to disk, or take up any space until something other than zero is written into it.

    0 讨论(0)
  • 2020-11-28 18:19

    You can do it programmatically:

    #include <unistd.h>
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <fcntl.h>
    #include <stdlib.h>
    
    int main() {
        int fd = creat("/tmp/foo.txt", 0644);
        ftruncate(fd, SIZE_IN_BYTES);
        close(fd);
        return 0;
    }
    

    This approach is especially useful to subsequently mmap the file into memory.

    use the following command to check that the file has the correct size:

    # du -B1 --apparent-size /tmp/foo.txt
    

    Be careful:

    # du /tmp/foo.txt
    

    will probably print 0 because it is allocated as Sparse file if supported by your filesystem.

    see also: man 2 open and man 2 truncate

    0 讨论(0)
  • 2020-11-28 18:23
    dd if=/dev/zero of=my_file.txt count=12345
    
    0 讨论(0)
  • 2020-11-28 18:27

    you could do:

    [dsm@localhost:~]$ perl -e 'print "\0" x 100' > filename.ext
    

    Where you replace 100 with the number of bytes you want written.

    0 讨论(0)
提交回复
热议问题