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

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

    You can do it programmatically:

    #include 
    #include 
    #include 
    #include 
    #include 
    
    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

提交回复
热议问题