/*
	CreateRandomFile.C  -  Utility to create large test files

   Copyright (C) Kay Gorontzi, October 2010

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

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

// You may increase this as large as you like
// or simply give a command line argument
#define MAXSIZE (2 * 1024LL * 1024LL * 1024LL)

int main(int argc, char *argv[])
   {
   long long Size, max;
   double s;
   int   f, dup;
   char *m;

   if (2==argc && 0==strcmp("-h", argv[1]))
   	{
   	printf("USAGE:  %s [<maximum size>]\n", *argv);
   	return(0);
   	}

   srand(time(0));

	max = MAXSIZE;
	if (argc > 1)  sscanf(argv[1], "%lld", &max);

   s = ((double)rand()) / RAND_MAX;
   s = max * s;
   Size = (unsigned long long)s;

   dup = (rand() % 100) + 1;

   Size = Size / dup + 1;

	printf("Writing %d x %lld random bytes (%lld MByte) ", dup, Size, Size*dup/1024/1024);
	fflush(stdout);

	m = (char*)malloc(Size);

   for (long long i=0; i<Size; ++i)
   	{
     	m[i]=(char)rand();
    	}

   f = open("RData", O_WRONLY | O_TRUNC | O_CREAT, 0666);
   for (int n=0; n<dup; ++n)
   	{
		printf(".");
		fflush(stdout);
		write(f, m, Size);
   	}
   close(f);
   free(m);

   printf("\n");
   return(Size);
   }
