This is from main:
Code:
if(cmd == 1) //cat command
{
cat_arg = getArgument(args+1, cmdline); //get 1st argument
//args is an int that starts at 0; args+1 represents the 1st...
//...argument after the command given; so the 1st parameter...
//...is the location on the command line
FILE *cat_file; //file to read from
//while there are still arguments
while(cat_arg != NULL)
{
args++;
cat_file = fopen(cat_arg, "r"); //open file
//check if file was opened
if(cat_file != NULL)
{
buffer = fgetc(cat_file); //read a char from the file
while(buffer != EOF)
{
fprintf(stdout, "%c", buffer); //write to stdout
buffer = fgetc(cat_file); //read from the file
}
}
else
fprintf(stderr, "cat: %s: No such file", cat_arg);
fclose(cat_file); //close the file
cat_arg = getArgument(args+1, cmdline); //get next arg
}
args = 0; //reset the argument counter
}
Here is getArgument:
Code:
/*
* char *getArgument(int which,char *command_line)
*
* Given a command string and a position, this function
* returns the argument at that position in the string.
* Counting should begin with the first word after the
* command. For example:
*
* char *arg1 = getArgument(1, "cat file1 file2");
*
* . . . will return "file1". If there are no arguments
* at the position specified by which, then the
* function should return NULL.
*/
char *getArgument(int which, char *command_line)
{
char *cpy_cmdline; //stores a copy of the paramter...
//...command_line
char *cmd; //stores the command given (1st argument in list)
char *arg; //stores an argument from the command line
int argCount = 0; //keeps track of the arguments
//copy the parameter command_line and store it in cpy_cmdline
cpy_cmdline = (char *)malloc(strlen(command_line)+1);
strcpy(cpy_cmdline, command_line);
cmd=strtok(cpy_cmdline, " \n\t"); //store the command
//if there are still arguments to extract
if(argCount < which)
{
//extract the 1st argument
arg = strtok(NULL, " \n\t");
argCount++;
//continue extracting arguments until the correct argument
//has been extracted
while(argCount < which)
{
arg = strtok(NULL, " \n\t");
argCount++;
}
}
return arg;
}