Assuming the input could be either ./test -v abc.txt
or ./test abc.txt
int main(int argc, char *argv[])
{
char *filename = argv[1];
bool verbose = false;
handleCommandLine(argv, filename, &verbose);
.
.
.
.
.
void handleCommandLine(char *argv[], char *filename, bool *verbose)
{
if (strcmp(argv[1], "-v") == 0)
{
printf("initialize\n");
*verbose = true;
strcpy(filename, argv[2]); <===== this gets illegal instruction4 when I execute
}
}
when I execute ./test -v test abc.txt
, I get illegal instruction4
Can someone help ? Thank you
CodePudding user response:
The comments already answered why you were getting an error. Here is working implementation:
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
void handleCommandLine(int argc, char **argv, char **filename, bool *verbose) {
for(int i = 1; i < argc; i ) {
if(!strcmp(argv[i], "-v")) {
*verbose = 1;
// skip "test" arg to -v?
i ;
continue;
}
// filename will be the last argument
*filename = argv[i];
}
}
int main(int argc, char *argv[]) {
char *filename = NULL;
bool verbose = false;
handleCommandLine(argc, argv, &filename, &verbose);
printf("filename=%s, verbose=%d\n", filename, verbose);
return 0;
}
and here some test output (as /usr/bin/test is a thing, consider using a better name for your program):
./test -v
filename=(null), verbose=1
./test -v test abc.txt
filename=abc.txt, verbose=1
./test abc.txt
filename=abc.txt, verbose=0