Reputation: 1877
While trying to take some arguments for C. I found it really difficult to get argv[]
to work. I have:
int main(int argc, char *argv[])
{
void updateNext();
void fcfs();
void spn();
void srt();
fp = fopen(argv[0],"r");
op = fopen("output.dat","a+");
if (strcmp(argv[1],"FCFS")!=0)
{
fcfs();
}
if (strcmp(argv[1],"SPN")!=0)
{
spn();
}
if (strcmp(argv[1],"SRT")!=0)
{
srt();
}
}
I would like to enter something in a format of myprog input.data FCFS
, but the above code gives me an error for "float point exception" the exception is gone after I hard code input.dat
as a string in the program. Something wrong with argv[0]
perhaps?
Upvotes: 0
Views: 431
Reputation: 994599
In C, argv[0]
is the name of your program (or more precisely, the first word the user typed on the command line to run your program, if run from a shell).
So, avoiding argv[0]
for your purposes, you'll want to look at argv[1]
for the file name and argv[2]
for the other parameter.
This would have been clear if you had used a debugger to trace through your program, or simply printed the value before you used it:
printf("using file name %s\n", argv[0]);
fp = fopen(argv[0],"r");
It's also a good idea to check that you have sufficient command line parameters by validating argc
before accessing argv
:
if (argc < 3) {
fprintf(stderr, "not enough command line parameters\n");
exit(1);
}
Upvotes: 7
Reputation: 182734
In C argv[0]
is typically the name with which the program was called. You're looking for argv[1]
and argv[2]
.
As side notes:
argc
before touching argv
argv[0]
contains the name of the program or even something sensibleUpvotes: 5