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?
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?
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.
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.
dd if=/dev/zero of=upload_test bs=file_size count=1
Where file_size
is the size of your test file in bytes
The trouble with the approaches using dd and perl is that they actually have to write every byte of the file. Using an approach like this you wouldn't have to.
#include <stdio.h>
int main ()
{
FILE * pFile;
int filesize = 12345;
pFile = fopen ( "myfile.txt" , "w" );
fseek ( pFile , filesize , SEEK_SET );
fputs ( "" , pFile );
fclose ( pFile );
return 0;
}
This will just allocate a large file and doesn't actually need to write many bytes to do so.
Disclaimer: I have not compiled or tested this code.
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.
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 proceeding 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
But:
# du /tmp/foo.txt
will return 0 because it is allocated as Sparse file.
see also: man 2 open and man 2 truncate