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?
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 atargv[1]for the file name andargv[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:
It’s also a good idea to check that you have sufficient command line parameters by validating
argcbefore accessingargv: