Example: Copying Multiple Files to Standard Output
Appendix A), which is called at the start of the program. This function, included on the Web site and used throughout the book, evaluates command line option flags and returns the argv index of the first file name. Use Options in much the same way as getopt is used in many UNIX programs.
Program 2-3. cat: File Concatenation to Standard Output
/* Chapter 2. cat. */
/* cat [options] [files] Only the -s option, which suppresses error
reporting if one of the files does not exist. */
#include "EvryThng.h"
#define BUF_SIZE 0x200
static VOID CatFile (HANDLE, HANDLE);
int _tmain (int argc, LPTSTR argv [])
{
HANDLE hInFile, hStdIn = GetStdHandle (STD_INPUT_HANDLE);
HANDLE hStdOut = GetStdHandle (STD_OUTPUT_HANDLE);
BOOL DashS;
int iArg, iFirstFile;
/* DashS will be set only if "-s" is on the command line. */
/* iFirstFile is the argv [] index of the first input file. */
iFirstFile = Options (argc, argv, _T ("s"), &DashS, NULL);
if (iFirstFile == argc) { /* No input files in arg list. */
/* Use standard input. */
CatFile (hStdIn, hStdOut);
return 0;
}
/* Process each input file. */
for (iArg = iFirstFile; iArg < argc; iArg++) {
hInFile = CreateFile (argv [iArg], GENERIC_READ,
0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hInFile == INVALID_HANDLE_VALUE && !DashS)
ReportError (_T ("Cat file open Error"), 1, TRUE);
CatFile (hInFile, hStdOut);
CloseHandle (hInFile);
}
return 0;
}
/* Function that does the work:
/* read input data and copy it to standard output. */
static VOID CatFile (HANDLE hInFile, HANDLE hOutFile)
{
DWORD nIn, nOut;
BYTE Buffer [BUF_SIZE];
while (ReadFile (hInFile, Buffer, BUF_SIZE, &nIn, NULL)
&& (nIn != 0)
&& WriteFile (hOutFile, Buffer, nIn, &nOut, NULL));
return;
}
