/*
	DevZero
	---------
	This program is providing something like a /dev/zero device known from
	unix machines. As long as there is no such device on windows, I decided
	to create my own. 
	Today, I saw that dd for windows (http://www.chrysocome.net/dd) is also
	providing virtual devices in the actual beta version (0.4beta1). Maybe
	that's an easier way to create null character files.
	
	This code is evolved out of a tiny idea and some boredom, so it's free
	to use, distribute, modify and bla bla bla... 
	Nothing special, so no license and so on.
	
	Author: Martin Albrecht <martin.albrecht@javacoffee.de>
	Website: http://code.javacoffee.de
	Date: 03.01.2009
*/

#include <stdio.h>
#include <math.h> //For pow()

int main(int argc, char *argv[])
{
  double MAXCNT;
  char nChar = 0x00;
  char tmp;
  char *filename = "";
  double count = 0;
  double i;
  FILE *fd;
  
  /* Usage */
  if( argc != 3 ){
      printf("usage: %s <count> <file name>\n\nExample: %s 1024 foo.txt\nThis creates a 1024 byte file with the name foo.txt in the current folder.\n", argv[0], argv[0]);
      return 0;
  }
  
  /* Get the maximum count of bytes we can handle
	  Normally, this would be 64 bit (8 byte for a double) on x86 32 bit machines,
	  but it is machine dependend and so we calculate it at startup
  */
  MAXCNT = pow(2,(sizeof(double)*8));  

  /* Easteregg: Value 0 as count writes the maximum byte count. */
  if( atoi(argv[1]) == 0 )
      count = MAXCNT;
  else
      count = atoi(argv[1]);
      
  if( count > MAXCNT ){
      printf("Error: Given number is a bit too large, my friend...\nMaximum is: %.0f.", MAXCNT);
      return 1;
  }
  
  filename = argv[2];
  if( !filename || filename == "" ){
      printf("Error: No valid filename!\n");
      return 1;
  }
  else{
       fd = fopen(filename, "w+");
       if( fd == NULL || !fd ){
           printf("Error: File could not be opened!\n");
           return 1;
       }
  }
  
  printf("Okay, I try to write %.0f bytes, now...\n", count);
  for( i=0; i<=count-1; i++ ){
       tmp = putc(nChar, fd);
       if( tmp != nChar ){
           printf("Error: Something went wrong, as I tried to write the file...\n");
           return 1;
       }
  }

  printf("\nWritten %.0f null characters!\nMax count was: %.0f bytes.", i, MAXCNT);
  fclose(fd);
  return 0;
}
