随机文件生成器代码?

时间:2010-08-09 23:54:34

标签: random

是否有人使用简单的shell脚本或c程序来生成设置大小的随机文件 在linux下随机内容?

6 个答案:

答案 0 :(得分:13)

怎么样:

head -c SIZE /dev/random > file

答案 1 :(得分:3)

openssl rand可用于生成随机字节。 命令如下:

openssl rand [bytes] -out [filename]

例如,openssl rand 2048 -out aaa将生成一个名为aaa的文件,其中包含2048个随机字节。

答案 2 :(得分:2)

以下是一些方法:

的Python:

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

击:

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

使用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);
}

答案 3 :(得分:0)

的Python。称之为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) )

像这样使用

./make_random 1024 >some_file

这将向stdout写入1024个字节,您可以将其捕获到文件中。根据您的系统编码,这可能不会像Unicode一样可读。

答案 4 :(得分:0)

这是我在Perl中编写的一个快速的脏脚本。它允许您控制将在生成的文件中的字符范围。

#!/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);

使用:

./script.pl file 2048

这是一个较短的版本,基于S. Lott关于输出到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);
}

警告:这是我在Perl中编写的第一个脚本。永远。但似乎工作正常。

答案 5 :(得分:0)

您可以使用我用于在我的项目中生成测试数据的generate_random_file.py脚本(Python 3)。

  • 它适用于Linux和Windows。
  • 它非常快,因为它使用os.urandom()以256 KiB的块生成随机数据,而不是分别生成和写入每个字节。