Tuesday, July 14, 2009

Question about "int main(int argc, char *argv[])" in the C language?

I'm trying to help out a friend out understanding the C language for a class. I personally understand C++, never worked with C. His problem is that he has to write a program that gets a loop count from the command line, and then writes the process ID for each loop as it runs. We've made some progress with understanding other parts of how C works, but we aren't getting this argc and argv[] part. I know what they are, but not how to properly use them. Here is the code that he was given to start with:








#include %26lt;sys/types.h%26gt;


#include %26lt;unistd.h%26gt;





int main(int argc, char *argv[]) {


int count;


if (argc == 2)


count = atoi(argv[1]);


else


count = 10;





pid_t getpid(void);





}





=======================


Any help is greatly appreciated. I just need to understand how to use these parameters, then I should be able to use them properly in the code, and help him out... Thanks...

Question about "int main(int argc, char *argv[])" in the C language?
It looks like you are on the right track, and given the other answer you know what the parameters are and how they are used.





Im confused with how you are compiling and running your programme. The one you gave in the question should not put out any information. As a simple test, change your programme slightly to verify what you are finding on the command line:





include %26lt;sys/types.h%26gt;


#include %26lt;unistd.h%26gt;





int main(int argc, char *argv[]) {


int count;


int pid;





if (argc == 2)


count = atoi(argv[1]);


else


count = 10;





pid = getpid();





printf( "count=%d pid%d\n", count, pid );





}





=============


Just to make sure you are on the right track with compilation, if your programme is in prog.c try these commands:





gcc prog.c


a.out 6





Im assuming you have gcc, otherwise the command will be cc to compile and link. By default the output is a file called a.out and that is executable from the command line. If this worked, then you should see count=6 and pid=xxxxxx on the screen.





Hope this gets you a bit further.
Reply:When the application starts the command line is parsed and passed to the main function. The argc is the integer count of the parameters passed and argv is an array of char * that points to the string data containing each of the command line arguments. When parsed argv[0] equals the name of the application that was executed and argv[1..n] is each of the command line parameters.


No comments:

Post a Comment