1
Command Line Arguments
COMP 1002/1402
Purpose
- At times a program needs to know some
information during startup
- Examples:
Command Line Arguments COMP 1002/1402 Purpose At times a program - - PDF document
Command Line Arguments COMP 1002/1402 Purpose At times a program needs to know some information during startup Examples: A gaming program needs to know the maximum number of players that will participate A file copy program
– man printf
– ls –l
– cp infile outfile
– make –f myMakeFile
int main(void) { /* local definitions */ /* statements */ } int main(int argc, char *argv[]) { /* local definitions */ /* statements */ }
– a counter which “tells” the program how many arguments are passed to the program – an integer
– a list of argument which are passed to the program – an array of pointers to
argument
#include “stdio.h” #include “stdlib.h” #include “string.h” int main(int argc, char **argv) { int i; printf(“The program name is: %s \n”,argv[0]); printf(“The number of arguments: %d \n”,argc); for (i = 1; i < argc; i++) { printf(“argument[%d] = %s \n”, i, argv[i]); } return(0); }
– The program expects two arguments an input file and output file copyfiles in.txt out.c
– copyfiles – copyfiles in.txt – copyfiles in.txt out.c
#include “stdio.h” #include “stdlib.h” #include “string.h” #define NAME_SIZE 1024 char *getFileName(char *fileRole, char **fileName); void main(int argc, char **argv) { int i; char *inFile = NULL; /* a pointer to the name of the input file */ char *outFile = NULL; /* an pointer to the name of the output file */ switch(argc) { case 3: /* set the output file name */
case 2: /* set the input file name */ inFile = argv[1]; default: break; } if (inFile == NULL) getFileName(“input file”, &inFile); /* obtain input file name */ if (outFile == NULL) getFileName(“output file”, &inFile); /* obtain output file name */ /* other statements */ }
char *getFileName(char *fileRole, char **fileName) { char temp[NAME_SIZE]; /* a temporary array */ while (1) { printf(“Enter %s name:”); scanf(“%s”,temp); if (strlen(temp) >=1) break; printf(“file name must contain at least one character \n”); } *fileName = malloc(strlen(temp)+1); strcpy(*fileName, temp); return(*fileName); }