Генерация случайных файлов в Windows - PullRequest
28 голосов
/ 10 февраля 2009

У кого-нибудь есть способ генерировать файлы случайных данных в Windows? Я хотел бы сгенерировать 50 000 маленьких (2K) файлов в качестве примера.

Ответы [ 13 ]

0 голосов
/ 11 апреля 2017

Вы можете использовать VBA в Excel, если у вас ограниченные права на компьютере, на котором вы находитесь. Это создаст TXT-файлы с числом, необходимым для случайных чисел. Вероятно, не самый быстрый способ сделать это, хотя.

Sub rndcreate()

Application.ScreenUpdating = False
Application.DisplayAlerts = False

Dim sbook As Workbook
Dim i As Double
Dim upperbound, lowerbound, totalentries, totalfiles As Integer
Dim x, folder, file As String

'Set output location

folder = "C:\test\"

'Number of files created and entries in files as below

totalfiles = 1
totalentries = 150
upperbound = 99999
lowerbound = 1

For p = 1 To totalfiles

'Add new workbook to populate with data

Set sbook = Workbooks.Add

'Set file name

file = "randomdatafile" & p

For i = 1 To totalentries

    'Randomly created integers between your two bounds

    x = ((upperbound - lowerbound + 1) * Rnd + lowerbound)

    Range("A" & i) = x

Next

ActiveWorkbook.SaveAs Filename:=folder & file & ".txt", FileFormat:=xlTextWindows
ActiveWorkbook.Close

Next

End Sub
0 голосов
/ 10 августа 2016

Да, fsutil великолепен, но не генерирует случайные данные, только нули ASCII.

Я не помню, где я нашел это, но в поисках в Google в эти дни я все еще могу найти это в:

Я не знаю, сколько лет этой программе, но, по крайней мере, столько же лет, сколько ваш вопрос, возможно, несколько старше.

В любом случае, вот программа на C, которая создает файлы с результатом теста хи-квадрат 0:

// ------------------------------------------------------------     
// Name: random.c  (program to create random files)
//     
// This "no-frills" program creates files with the following 
// characteristics: 
//
//    (1) Byte sequences are random (no predictability);
//    (2) Files produced are binary files; 
//    (3) File sizes are multiples of 256; 
//    (4) Files will have a chi-squared test result of 0
//        (see analyze.exe by Wenger for explanation)
//  
//              Programmer:  Scott Wenger
//                           Box 802
//                           Stevens Point, WI 54481
//                           panther@wctc.net
//
//       Note:  part of this code is from Knuth Volume II
// 
//  Enhancements and modifications of this program are left 
//  to the imagination and creativity of the programmer.
//  Check your compiler for required header files.  You may 
//  need to include the iostream header.
//
//  Random files are of potential use to cryptographers
//  for the purpose of encryption.  
//  
//  To analyze files produced by this program, see 
//  the analyze.exe program by Scott Wenger (found at
//  http://www.coredcs.com/sware.html)
// ------------------------------------------------------------


// This program works in the following way:
// The time is used to seed the random number generator.
// Using Knuth's algorithm, random numbers are generated
// in the range of 0 to 255 (corresponding to 256 ASCII chars.)
// When random numbers are generated they are marked as used and 
// are not re-used until all 256 ASCII values appear.  Characters 
// are written to disk and the process continues until the
// desired file size is reached.  Output is a random binary file
// called random.bin (placed in the root directory)
// The controlled filesize along with the placeholder feature 
// of this code forces a very high degree of randomness in 
// the output file. 

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

void init_mm();
void clear_array(); 
int  number_range(int minval, int maxval);
int  number_mm();

static int rgiState[2 + 55]; 
int place_holder[256];          // to keep track of numbers already generated

int main()
{
  mainprogram();
  return 0;
}

int mainprogram()
{
  int ch; 
  int c_used = 0;  // counter of chars in placeholder
  int done = 0; 
  int random;

  char buffer[2];

  long x;
  long byte_size = 0L;
  FILE *fp;

  clear_array();
  init_mm();  // seed random number generator

  // create a random file of length specified by user
  printf("\nrandom.exe originally by Scott Wenger");
  printf("\nThis program creates a random binary file.\n");
  printf("\nPlease specify length of random file to create (in megabytes): ");  

  scanf("%ld", &byte_size);

  while (byte_size > 1000 || byte_size <= 0 )
  {
    printf("\nWill not create files larger than a gigabyte! ");
    printf("\nPlease specify length of random file to create (in megabytes): ");
    flushall();
    scanf("%ld", &byte_size);
  }

  byte_size = byte_size * 1024 * 1024;

  if ( (fp = fopen("random.bin", "wb"))  == NULL) {
    fprintf(stderr, "\nOutput file (random.bin) could not be created.");      
    fflush(stdout);
    exit(1);
  }

  for (x = 0L; x < byte_size; x++) {

    if (c_used == 256) {
      clear_array();
      c_used = 0;
    }

    random = number_range(0, 255);    // use all ASCII values

    if ( *(place_holder + random) ) {  // already used, find another
      done = 0;
      while (!done) {
        random = number_range(0, 255);
        if ( *(place_holder + random) == 0) {
          *(place_holder + random) = 1;
          done = 1;
        }
      }         
    }
    else *(place_holder + random) = 1;  // use it and mark as used 

    c_used++;   // found next character so increment counter

    sprintf(buffer, "%c", random);  // convert ASCII value to char 
    ch = buffer[0];
    fputc(ch, fp); // write to file
  }

  fclose(fp);

  printf("\nDone. File \"random.bin\" was created (size: %ld bytes)", byte_size);
  printf("\nOutput file is in the root directory (c:\\random.bin)\n");
  return(0);
}

// ---------------------------------------------------------------------------------

void clear_array()
{
  register int x;
  for (x = 0; x < 256; x++) 
    *(place_holder + x) = 0;
}

// ---------------------------------------------------------------------------------

int number_mm()
{
    int *piState;
    int iState1;
    int iState2;
    int iRand;

    piState     = &rgiState[2];
    iState1     = piState[-2];
    iState2     = piState[-1];
    iRand       = ( piState[iState1] + piState[iState2] )
                & ( ( 1 << 30 ) - 1 );
    piState[iState1]    = iRand;

    if ( ++iState1 == 55 )  iState1 = 0;
    if ( ++iState2 == 55 )  iState2 = 0;

    piState[-2]     = iState1;
    piState[-1]     = iState2;

    return(iRand >> 6);
}

// ---------------------------------------------------------------------------------

//  Generate a random number.

int number_range( int minval, int maxval )
{
  int power, number;

  if ( ( maxval = maxval - minval + 1 ) <= 1 ) return (minval);

  for ( power = 2; power < maxval; power <<= 1 )
    ;
  while ( ( number = number_mm( ) & ( power - 1 ) ) >= maxval )
    ;
  return(minval + number);
}

// ---------------------------------------------------------------------------------

// Mitchell-Moore algorithm from Knuth Volume II. 

void init_mm( )
{
  int *piState;
  int iState;

  piState = &rgiState[2];
  piState[-2]   = 55 - 55;
  piState[-1]   = 55 - 24;
  piState[0]    = ( (int) time( NULL ) ) & ( ( 1 << 30 ) - 1 );
  piState[1]    = 1;

  for ( iState = 2; iState < 55; iState++ ) 
  {
    piState[iState] = ( piState[iState-1] + piState[iState-2] )
                      &  ( ( 1 << 30 ) - 1 );
  }
}

// -------------------- End -------------------------------------------------------
0 голосов
/ 10 февраля 2009

Ну, технически вы могли бы написать что-нибудь, чтобы сделать это для вас.
Я не знаю ничего конкретного ... но проще всего было бы создать TEXT-файл определенного размера (например, 2K) ... затем написать пакетный файл, чтобы скопировать его 50000 раз.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...