I have a script that writes to a few files but I need them a specific size. So I'm wondering if there's a way of appending a specific number of null bytes from /dev/zero or however to a file?

link|improve this question

67% accept rate
feedback

5 Answers

You can try this as well

dd if=/dev/zero bs=1 count=NUMBER >> yourfile

This will read from /dev/zero and append to yourfile NUMBER bytes.

link|improve this answer
feedback

truncate is more faster than dd. To grow the file with 10 bytes use:

 truncate -s +10 file.txt 
link|improve this answer
Its much faster because it'll generate a sparse file, which is what you want most of the time—but if you don't want a sparse file, the dd approach will work. – derobert Dec 26 '11 at 23:42
feedback

my first guess would be:

dd if=/dev/zero of=myfile bs=1 count=nb_of_bytes seek=$(stat -c%s myfile)

Basically, this command tells dd to "go" at the end of the file and add some bytes previously read from /dev/zero.

Regards,

link|improve this answer
feedback
cat "your file" /dev/zero | head -c "total number of bytes"

or

head -c "number of bytes to add" /dev/zero >> "your_file"

and to compute the size more easily:

head -c $(( "total number of bytes" - $(stat -c "%s" "your_file") )) /dev/zero >> "your_file"
link|improve this answer
feedback

If you are padding your file with null bytes, my guess is that you are manipulating the file in a char * in C. If this is the case, you might not need to pad the file with null bytes, only adding a null byte at the end of the file and then padding it with random bytes could be enough. In this case, the C program bellow would be very efficient (to be used only on files smaller than the 2nd parameter, otherwise data would be overwritten). It might even do what you want (padding with null bytes) as the lseek function definition states that:

The lseek() function shall allow the file offset to be set beyond the end of the existing data in the file. If data is later written at this point, subsequent reads of data in the gap shall return bytes with the value 0 until data is actually written into the gap.

In this case, the 1st call to lseek and write could be removed. But tests should be done on your system 1st...

#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>

/* 1st parameter: a file name, 2nd parameter: a file size. */
int main(int argc, char ** args) {
   int nfd = open(args[1], O_WRONLY);
   lseek(nfd, 0, SEEK_END);
   write(nfd, "\0", 1);
   lseek(nfd, atoi(args[2]) - 1, SEEK_SET);
   write(nfd, "\0", 1);
   close(nfd);
   return 0;
}
link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.