Hamilton LaboratoriesHamilton C shell 2012User guideSamples

blksize.c

Oregon Coast

blksize.c
Previous | Next

/***************************************************************************/
/*                                                                         */
/*                                                                         */
/*       Read from Stdin, Write to Stdout, using specified Blocksize       */
/* Copyright (c) 1994-2012 by Hamilton Laboratories.  All rights reserved. */
/*                                                                         */
/*                                                                         */
/***************************************************************************/

/* blksize.c:  Accepts just one (optional) argument, the
               blocksize desired, in bytes.  */

#include <windows.h>
#include <stdlib.h>

void main( int argc, char **argv )
   {
   HANDLE Stdin = GetStdHandle(STD_INPUT_HANDLE),
      Stdout = GetStdHandle(STD_OUTPUT_HANDLE);
   char *buffer, *p;
   DWORD length, blocksize, remaining;
   SYSTEM_INFO sysinfo;

   /* First arg is blocksize.  If missing, default to 512 bytes. */
   blocksize = argc > 1 ? atoi(argv[1]) : 512;

   /* Allocate the buffer, ensuring that it's page-aligned so we
      won't have problems doing i/o to/from a device such as a tape
      or diskette. */
   GetSystemInfo(&sysinfo);
   buffer = (char *)(((ULONG)malloc(blocksize + sysinfo.dwPageSize) +
         sysinfo.dwPageSize) & ~(sysinfo.dwPageSize - 1));

   while (ReadFile(Stdin, buffer, blocksize, &length, NULL) && length)
      {
      if (remaining = blocksize - length)
         {
         /* Apparently reading from a pipe or the console and getting less
            than a full blocksize number of characters.  Keep reading until
            we have enough to for a whole blocksize to output (or until
            End-Of-File). */
         p = buffer + length;
         while (remaining &&
               ReadFile(Stdin, p, remaining, &length, NULL) && length)
            {
            remaining -= length;
            p += length;
            }
         length = blocksize - remaining;
         }
      WriteFile(Stdout, buffer, length, &length, NULL);
      }

   CloseHandle(Stdin);
   CloseHandle(Stdout);
   ExitProcess(0);
   }

Previous | Next