I currently have a program, myprogram.c, that can be invoked with command line arguments such as myprogram testfile
. This will read in text from testfile
, assuming it exists, and the function spaces()
will alter the text and print it to stdout. However, I want to be able to invoke the program like myprogram testfile -o outputfile
so that instead of printing to stdout, the output is written to outputfile
. How would I go about doing this?
What follows is the general structure of my main.
int main (int argc, char *argv[])
{
char *a;
char *prev_line[999];
size_t len = 0;
size_t read;
/* if there is more than one argument */
if (argc > 1)
{
a = malloc (MAX_NAME_SZ * sizeof (char));
int i = 1;
FILE *fp;
while (i < argc)
{
fp = fopen (argv[i], "r");
if (fp == NULL)
{
/*Error statement in case file doesn't exist */
}
else
{
char* line = NULL;
while ((read = getline(&line, &len, fp)) != -1) {
/*code to create char array a */
}
}
free(line);
fclose (fp);
}
i++;
}
}
else /* if no command line arguments */
{
/* get array a from stdin*/
spaces (a);
return 0;
}
spaces (a);
return 0;
}
Any help or solution is greatly appreciated. Thanks!