Random file generator code?

2019-04-10 00:43发布

问题:

Does anyone have a simple shell script or c program to generate random files of a set size with random content under linux?

回答1:

How about:

head -c SIZE /dev/random > file


回答2:

openssl rand can be used to generate random bytes. The command is below:

openssl rand [bytes] -out [filename]

For example,openssl rand 2048 -out aaa will generate a file named aaa containing 2048 random bytes.



回答3:

Here are a few ways:

Python:

RandomData = file("/dev/urandom", "rb").read(1024)
file("random.txt").write(RandomData)

Bash:

dd if=/dev/urandom of=myrandom.txt bs=1024 count=1

using C:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int byte_count = 1024;
    char data[4048];
    FILE *fp;
    fp = fopen("/dev/urandom", "rb");
    fread(&data, 1, byte_count, fp);
    int n;

    FILE *rand;
    rand=fopen("test.txt", "w");
    fprintf(rand, data);
    fclose(rand);
    fclose(rand);
}


回答4:

Python. Call it make_random.py

#!/usr/bin/env python
import random
import sys
import string
size = int(sys.argv[1])
for i in xrange(size):
    sys.stdout.write( random.choice(string.printable) )

Use it like this

./make_random 1024 >some_file

That will write 1024 bytes to stdout, which you can capture into a file. Depending on your system's encoding this will probably not be readable as Unicode.



回答5:

Here's a quick an dirty script I wrote in Perl. It allows you to control the range of characters that will be in the generated file.

#!/usr/bin/perl

if ($#ARGV < 1) { die("usage: <size_in_bytes> <file_name>\n"); }

open(FILE,">" . $ARGV[0]) or die "Can't open file for writing\n";

# you can control the range of characters here
my $minimum = 32;
my $range = 96;

for ($i=0; $i< $ARGV[1]; $i++) {
    print FILE chr(int(rand($range)) + $minimum);
}

close(FILE);

To use:

./script.pl file 2048

Here's a shorter version, based on S. Lott's idea of outputting to STDOUT:

#!/usr/bin/perl

# you can control the range of characters here
my $minimum = 32;
my $range = 96;

for ($i=0; $i< $ARGV[0]; $i++) {
    print chr(int(rand($range)) + $minimum);
}

Warning: This is the first script I wrote in Perl. Ever. But it seems to work fine.



回答6:

You can use my generate_random_file.py script (Python 3) that I used to generate test data in a project of mine.

  • It works both on Linux and Windows.
  • It is very fast, because it uses os.urandom() to generate the random data in chunks of 256 KiB instead of generating and writing each byte separately.


标签: random