Advertisement
Guest User

Cat.c

a guest
Sep 10th, 2013
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.50 KB | None | 0 0
  1. /* Chapter 2. cat. */
  2. /* cat [options] [files]
  3.     Only the -s option is used. Others are ignored.
  4.     -s suppresses error report when a file does not exist */
  5.  
  6. #include "Everything.h"
  7.  
  8. #define BUF_SIZE 0x200
  9.  
  10. static VOID CatFile (HANDLE, HANDLE);
  11. int _tmain (int argc, LPTSTR argv [])
  12. {
  13.     HANDLE hInFile, hStdIn = GetStdHandle (STD_INPUT_HANDLE);
  14.     HANDLE hStdOut = GetStdHandle (STD_OUTPUT_HANDLE);
  15.     BOOL dashS;
  16.     int iArg, iFirstFile;
  17.  
  18.     /*  dashS will be set only if "-s" is on the command line. */
  19.     /*  iFirstFile is the argv [] index of the first input file. */
  20.     iFirstFile = Options (argc, argv, _T("s"), &dashS, NULL);
  21.  
  22.     if (iFirstFile == argc) { /* No files in arg list. */
  23.         CatFile (hStdIn, hStdOut);
  24.         return 0;
  25.     }
  26.    
  27.     /* Process the input files. */
  28.     for (iArg = iFirstFile; iArg < argc; iArg++) {
  29.         hInFile = CreateFile (argv [iArg], GENERIC_READ,
  30.                 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  31.         if (hInFile == INVALID_HANDLE_VALUE) {
  32.             if (!dashS) ReportError (_T ("Cat Error: File does not exist."), 0, TRUE);
  33.         } else {
  34.             CatFile (hInFile, hStdOut);
  35.             if (GetLastError() != 0 && !dashS) {
  36.                 ReportError (_T ("Cat Error: Could not process file completely."), 0, TRUE);
  37.             }
  38.             CloseHandle (hInFile);
  39.         }
  40.     }
  41.     return 0;
  42. }
  43.  
  44. static VOID CatFile (HANDLE hInFile, HANDLE hOutFile)
  45. {
  46.     DWORD nIn, nOut;
  47.     BYTE buffer [BUF_SIZE];
  48.  
  49.     while (ReadFile (hInFile, buffer, BUF_SIZE, &nIn, NULL) && (nIn != 0)
  50.             && WriteFile (hOutFile, buffer, nIn, &nOut, NULL));
  51.  
  52.     return;
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement