/*********************************************************************
 * Author: B. Alex Bridges                                           *
 * File: lab10.c                                                     *
 * Class: CPSC-202 Lab Section 3                                     *
 * Project: Lab 10 - Getting Information                             *
 * Purpose: This program will determine the number of files that are *
 *          larger than 1000 bytes in the current directory.         *
  *********************************************************************/

/* INCLUDES */
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>

/* CONSTANTS */
#define c_MaxLngth 255+1


/*********************************************************************
 * MAIN FUNCTION                                                     *
 *********************************************************************/
int main(void)
{
	/* --LOCAL VARIABLES-- */
	pid_t pid_Value;		/* THE PROCESS ID VALUE */
	int intA_Pipe[2];		/* THE PIPE */
	char charA_Current[1];		/* THE CURRENT READ CHARACTER */
	char charA_Line[c_MaxLngth];	/* THE LINE OF TEXT */
	char charA_Temp;		/* TEMP. FILE NAME */
	FILE *file_Temp;		/* TEMP. FILE POINTER */
	int fd_Temp;			/* TEMP. FILE DESCRIPTOR */

	/* --FUNCTION-- */
	/* HEADER */
	system("clear");
	printf("B. Alex Bridges\n"
	       "CPSC-202, Winter 1998\n"
	       "The Getting Information Program\n"
	       "\n");

	/* 1. CREATE A PIPE */
	if( pipe(intA_Pipe) < 0 )
	{
		perror("pipe");
		exit(-1); /* ERROR */
	} /* if */
	
	/* 2. FORK A PROCESS */
	if( ( pid_Value = fork() ) < 0 )
	{
		perror("fork");
		exit(-1); /* ERROR */
	} /* if */
	
	/* --CHILD-- */
	/* 3. RE-DIRECT STANDARD OUT */
	/* 4. CHILD PROCESS EXECUTES ls -la */
	if(pid_Value == 0)
	{
		dup2(intA_Pipe[1], 1);
		close(intA_Pipe[0]);
		
		execl("/usr/bin/ls", "ls", "-ll", NULL);
		
		/* IF execl FAILS */
		perror("ERROR: ls");
		exit(-1); /* ERROR */
	} /* if */
	
	/* --PARENT-- */
	/* 7. READ IN INFO. FROM ls */
	close(intA_Pipe[1]);
	if( read(intA_Pipe[0], charA_Current, 1) < 0 )
	{
		perror("ERROR: read");
		exit(-1); /* ERROR */
	} /* if */
	else if(charA_Current != `\n`)
		strcat(charA_Line, charA_Current);
	else
		fprintf(stderr, "Line = '%s`", charA_Line); /* DEBUG */

	/* 5. PARENT WAIT FOR CHILD TO FINISH */
	while( wait( (int *) 0 ) != pid_Value )
		continue;
	
	/* 6. CONVERT FILE DESCRIPTOR TO A FILE POINTER */
	strcpy(charA_Temp, "/tmp/lab10_XXXXXX");
	mktemp(charA_Temp);
	fd_Temp = open(charA_Temp, "r");
	File_Temp = fdopen(fd_Temp, "r");
	
	return(0);
} /* main */
