ctzmsc3

randasc.c

Apr 2nd, 2012
21
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.30 KB | None | 0 0
  1. /*
  2.  * randasc.c
  3.  * Generates random ASCII bytes (values 0x20 to 0x7E)
  4.  * Copyright 2012 ctzmsc3
  5.  * License: Do whatever you want.
  6.  */
  7.  
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10.  
  11. int
  12. main(int argc, char** argv)
  13. /* first arg is number of chars desired
  14.  * second is number of chars per line before line break
  15.     (defaults to 0, or no breaks)
  16.  * third is randomness source (defaults to /dev/urandom)
  17.  */
  18. {
  19.   FILE* rando;
  20.   int c, n, i;
  21.   unsigned int s=0;
  22.   char* src;
  23.   char a;
  24.   if (argc < 2)
  25.     {
  26.       fprintf(stderr, "Error: not enough args\n");
  27.       return 1;
  28.     }
  29.   n=atoi(argv[1]);
  30.   if (argc >= 3)
  31.     s=atoi(argv[2]);
  32.   if (argc >= 4)
  33.     src=argv[3];
  34.   else
  35.     src="/dev/urandom";
  36.   rando=fopen(src, "r");
  37.   if (rando == NULL)
  38.     {
  39.       fprintf(stderr, "Error: could not open %s\n", src);
  40.       return 1;
  41.     }
  42.   /*do stuff*/
  43.   i=0;
  44.   do
  45.     {
  46.       c=getc(rando);
  47.       if (c == EOF)
  48.         {
  49.           fprintf(stderr, "Error: EOF before finish\n");
  50.           fclose(rando);
  51.           return 1;
  52.         }
  53.       a=c%128; /*eliminate MSB*/
  54.       if (a >= 0x21)
  55.         {
  56.           putchar(a-1); /*eliminate 7f*/
  57.           i++;
  58.           if (s && !(i%s))
  59.             putchar('\n');
  60.         }
  61.     } while (i<n);
  62.   fclose(rando);
  63.   putchar('\n');
  64.   return 0;
  65. }
Advertisement
Add Comment
Please, Sign In to add comment