2009-02-10 14 views
25

Qualcuno ha un modo per generare file di dati casuali in Windows? Vorrei generare 50.000 piccoli file (2K) come esempio.Generazione di file casuali in Windows

+2

Potrebbe condividere con noi se si desidera file di testo o file binari? Puoi anche commentare su quali linguaggi di programmazione hai accesso (se ce ne sono)? Hai installato MS Office? Inoltre, non molto rilevante, ma quale versione di Windows stai usando? – user62572

risposta

0

Bene, tecnicamente potresti scrivere qualcosa per farlo per te.
Non so nulla di specifico .. ma il modo più semplice sarebbe quello di creare un file TEXT di una dimensione specifica (2K per esempio) .. quindi scrivere un file batch per copiarlo 50000 volte.

3

Dovrai creare i file nel modo normale e quindi popolarli con dati randomizzati, probabilmente da una funzione rand() di qualche tipo.

Dipende davvero dal linguaggio di programmazione. Windows di per sé non fornirà questa funzionalità.

Esistono numerosi linguaggi di programmazione che possono essere facilmente eseguiti, inclusi gli script batch/CMD di Windows di base. Che lingua sei interessato a usare?

28

È possibile eseguire fsutil in un ciclo batch per creare file di qualsiasi dimensione.

fsutil file createnew filename.extension 2000 
+0

Ho appena trovato quell'utilità. Non sapevo che esistesse prima. http://thebackroomtech.com/2009/01/16/howto-generate-many-files-of-a-particular-size-in-windows/ – beach

+28

Tuttavia, non crea dati casuali. Solo file vuoti. – beach

+0

E sembra richiedere autorizzazioni di amministratore. Andando con il powershell. –

5

Dato che non si specifica una lingua, ne selezionerò semplicemente una a caso. Ecco uno script di PowerShell per farlo:

$rootDir = 'C:\Temp\TestRandomFiles\' 
$baseFile = $rootDir + "base.txt" 
$desiredFileSize = 2*1KB 
$fileCount = 50000 
"start" | Out-File -Filepath $baseFile 
While ($(Get-ChildItem -path $baseFile).Length -lt $desiredFileSize) 
{ 
    $(Get-ChildItem -path $baseFile).Length | Out-File $baseFile -APPEND 
} 
for($i=1;$i -lt $fileCount;$i++) 
{ 
    Copy-Item $baseFile "File$i.txt" 
} 

Dovrai cambiare le variabili in base ai parametri che vuoi ovviamente.

+1

oops ... ha mancato il requisito di dati casuali. È importante? Se è così posso modificarlo. – EBGreen

+1

Se sei un mago di PS, non credo che tu possa fare dati casuali perché sono curioso di sapere come è andata a finire! – Wil

+0

Non sono certo un mago, ma ci sono diversi modi. Fondamentalmente si identifica il set di dati che si desidera randomizzare (ad esempio 0-9 e a-Z), quindi si sceglie a caso da quel set per creare i dati per il file, quindi scriverlo sul file. Se ho una possibilità più tardi oggi, cambierò il codice sopra per usare dati casuali. – EBGreen

13

Sto usando Random Data File Creator e mi piace, crea file binari (cioè non file di testo) pieni di bit pseudo casuali, può creare rapidamente file molto grandi. Per usarlo per creare più file di piccole dimensioni è necessario copiarlo, il che sarebbe molto semplice dato che è a riga di comando.

13

È possibile utilizzare PowerShell per generare dati casuali a buon mercato per i file:

[Byte[]] $out = @() 
0..2047 | % {$out += Get-Random -Minimum 0 -Maximum 255} 
[System.IO.File]::WriteAllBytes("myrandomfiletest", $out) 

Questo utilizza un algoritmo con un seme preso dal clock di sistema, in modo da non usare questo per qualsiasi applicazioni crittografiche gravi.

Inoltre, prestare attenzione al degrado delle prestazioni di Get-Random quando si aumenta la dimensione del file di output. Altro su questo aspetto qui:

0

Sì, fsutil è grande, ma non genera dati casuali, solo i null ASCII.

non mi ricordo dove ho trovato questo, ma la ricerca su Google in questi giorni posso ancora trovare presso: http://www.private-files.com/other/random.c.txt

Non so quanti anni questo programma è, ma almeno vecchio come la tua domanda, probabilmente un po 'più vecchio.

Comunque ecco un programma in C che crea file con un risultato del test chi-quadrato di 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 
//       [email protected] 
// 
//  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 ------------------------------------------------------- 
2

Invece di utilizzare Get-Random per generare il testo come da user188737 & suggerimenti mguassa, ho migliorato il velocità utilizzando GUID.

Function New-RandomFile { 
    Param(
     $Path = '.', 
     $FileSize = 1kb, 
     $FileName = [guid]::NewGuid().Guid + '.txt' 
     ) 
    (1..($FileSize/128)).foreach({-join ([guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid -Replace "-").SubString(1, 126) }) | set-content "$Path\$FileName" 
} 

Questo ha richiesto 491 millisecondi per generare un file 1mb. Esecuzione:

New-RandomFile -FileSize 1mb 

UPDATE: metodo

Ho aggiornato la mia funzione di usare uno ScriptBlock, in modo da poter sostituire la 'NewGuid()' con tutto quello che vuoi.

In questo scenario, eseguo blocchi 1kb, poiché so che non creerò mai file più piccoli. Questo ha migliorato drasticamente la velocità della mia funzione!

Set-Content forza una NewLine alla fine, motivo per cui è necessario rimuovere 2 caratteri ogni volta che si scrive su file. L'ho sostituito con [io.file] :: WriteAllText() invece.

Function New-RandomFile_1kChunks { 
    Param(
     $Path = (Resolve-Path '.').Path, 
     $FileSize = 1kb, 
     $FileName = [guid]::NewGuid().Guid + '.txt' 
     ) 

    $Chunk = { [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + 
       [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + 
       [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + 
       [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + 
       [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + 
       [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + 
       [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + 
       [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid -Replace "-" } 

    $Chunks = [math]::Ceiling($FileSize/1kb) 

    [io.file]::WriteAllText("$Path\$FileName","$(-Join (1..($Chunks)).foreach({ $Chunk.Invoke() }))") 

    Write-Warning "New-RandomFile: $Path\$FileName" 

} 

Se non cura che tutti i pezzi sono casuali, si può semplicemente Invoke() la generazione del pezzo 1kb una volta .. questo migliora la velocità drasticamente, ma non farà l'intero file casuale.

Function New-RandomFile_Fast { 
    Param(
     $Path = (Resolve-Path '.').Path, 
     $FileSize = 1kb, 
     $FileName = [guid]::NewGuid().Guid + '.txt' 
     ) 

    $Chunk = { [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + 
       [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + 
       [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + 
       [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + 
       [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + 
       [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + 
       [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + 
       [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid + [guid]::NewGuid().Guid -Replace "-" } 
    $Chunks = [math]::Ceiling($FileSize/1kb) 
    $ChunkString = $Chunk.Invoke() 

    [io.file]::WriteAllText("$Path\$FileName","$(-Join (1..($Chunks)).foreach({ $ChunkString }))") 

    Write-Warning "New-RandomFile: $Path\$FileName" 

} 

Measure-Command tutti questi cambiamenti per generare un file di 10 MB:

Esecuzione New-RandomFile: 35.7688241 secondi.

Esecuzione di New-RandomFile_1kChunks: 25.1463777 secondi.

Esecuzione di New-RandomFile_Fast: 1.1626236 secondi.

0

È possibile utilizzare VBA in Excel se si dispone di autorizzazioni limitate sul computer in uso. Questo creerebbe file txt al numero richiesto con numeri casuali. Probabilmente non è il modo più rapido per farlo.

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 
2

One-liner in PowerShell:

$out = new-object byte[] 1048576; (new-object Random).NextBytes($out); [IO.File]::WriteAllBytes('d:\file.bin', $out) 

Questo è un fulmine veloce, rispetto a @ user188737 soluzione.

Problemi correlati