Arguments to main in C

245,633

Solution 1

The signature of main is:

int main(int argc, char **argv);

argc refers to the number of command line arguments passed in, which includes the actual name of the program, as invoked by the user. argv contains the actual arguments, starting with index 1. Index 0 is the program name.

So, if you ran your program like this:

./program hello world

Then:

  • argc would be 3.
  • argv[0] would be "./program".
  • argv[1] would be "hello".
  • argv[2] would be "world".

Solution 2

Imagine it this way

*main() is also a function which is called by something else (like another FunctioN)

*the arguments to it is decided by the FunctioN

*the second argument is an array of strings

*the first argument is a number representing the number of strings

*do something with the strings

Maybe a example program woluld help.

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

    printf("you entered in reverse order:\n");

    while(argc--)
    {
        printf("%s\n",argv[argc]);
    }

return 0;
}

it just prints everything you enter as args in reverse order but YOU should make new programs that do something more useful.

compile it (as say hello) run it from the terminal with the arguments like

./hello am i here

then try to modify it so that it tries to check if two strings are reverses of each other or not then you will need to check if argc parameter is exactly three if anything else print an error

if(argc!=3)/*3 because even the executables name string is on argc*/
{
    printf("unexpected number of arguments\n");
    return -1;
}

then check if argv[2] is the reverse of argv[1] and print the result

./hello asdf fdsa

should output

they are exact reverses of each other

the best example is a file copy program try it it's like cp

cp file1 file2

cp is the first argument (argv[0] not argv[1]) and mostly you should ignore the first argument unless you need to reference or something

if you made the cp program you understood the main args really...

Solution 3

For parsing command line arguments on posix systems, the standard is to use the getopt() family of library routines to handle command line arguments.

A good reference is the GNU getopt manual

Solution 4

Siamore, I keep seeing everyone using the command line to compile programs. I use x11 terminal from ide via code::blocks, a gnu gcc compiler on my linux box. I have never compiled a program from command line. So Siamore, if I want the programs name to be cp, do I initialize argv[0]="cp"; Cp being a string literal. And anything going to stdout goes on the command line??? The example you gave me Siamore I understood! Even though the string you entered was a few words long, it was still only one arg. Because it was encased in double quotations. So arg[0], the prog name, is actually your string literal with a new line character?? So I understand why you use if(argc!=3) print error. Because the prog name = argv[0] and there are 2 more args after that, and anymore an error has occured. What other reason would I use that? I really think that my lack of understanding about how to compile from the command line or terminal is my reason for lack understanding in this area!! Siamore, you have helped me understand cla's much better! Still don't fully understand but I am not oblivious to the concept. I'm gonna learn to compile from the terminal then re-read what you wrote. I bet, then I will fully understand! With a little more help from you lol

<> Code that I have not written myself, but from my book.

#include <stdio.h>

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

    printf("The following arguments were passed to main(): ");
    for(i=1; i<argc; i++) printf("%s ", argv[i]);
    printf("\n");

    return 0;
} 

This is the output:

anthony@anthony:~\Documents/C_Programming/CLA$ ./CLA hey man
The follow arguments were passed to main(): hey man
anthony@anthony:~\Documents/C_Programming/CLA$ ./CLA hi how are you doing?
The follow arguments were passed to main(): hi how are you doing?

So argv is a table of string literals, and argc is the number of them. Now argv[0] is the name of the program. So if I type ./CLA to run the program ./CLA is argv[0]. The above program sets the command line to take an infinite amount of arguments. I can set them to only take 3 or 4 if I wanted. Like one or your examples showed, Siamore... if(argc!=3) printf("Some error goes here"); Thank you Siamore, couldn't have done it without you! thanks to the rest of the post for their time and effort also!

PS in case there is a problem like this in the future...you never know lol the problem was because I was using the IDE AKA Code::Blocks. If I were to run that program above it would print the path/directory of the program. Example: ~/Documents/C/CLA.c it has to be ran from the terminal and compiled using the command line. gcc -o CLA main.c and you must be in the directory of the file.

Solution 5

Main is just like any other function and argc and argv are just like any other function arguments, the difference is that main is called from C Runtime and it passes the argument to main, But C Runtime is defined in c library and you cannot modify it, So if we do execute program on shell or through some IDE, we need a mechanism to pass the argument to main function so that your main function can behave differently on the runtime depending on your parameters. The parameters are argc , which gives the number of arguments and argv which is pointer to array of pointers, which holds the value as strings, this way you can pass any number of arguments without restricting it, it's the other way of implementing var args.

Share:
245,633
Anthony
Author by

Anthony

Updated on December 09, 2020

Comments

  • Anthony
    Anthony over 3 years

    I don't know what to do! I have a great understanding of C basics. Structures, file IO, strings, etc. Everything but CLA. For some reason I cant grasp the concept. Any suggestions, help, or advice. PS I am a linux user

  • Anthony
    Anthony over 13 years
    i use code::blocks IDE. ive never ran a program like that. ./program hello world. i understand the whole argc and argv thing i just dont understand what its doing why we use it and all that good stuff.
  • cdhowie
    cdhowie over 13 years
    Because that's how users supply information to command-line programs. If it weren't for command-line arguments, what would you suggest we use instead? stdin? Environment variables?
  • Anthony
    Anthony over 13 years
    so lets say i am printing Hello world to stdout. Thats stores hello world on the command line? hello is argv[1], world would be argv[2], and the program path is argv[0]? still lost!! Maybe im just a dumb ass lol
  • Anthony
    Anthony over 13 years
    And i don't understand y this is used in programs? Out of all the books I have, This section is the shortest! I guess theres really not much to them. Only me
  • cdhowie
    cdhowie over 13 years
    Printing (printf for example) writes to the program's stdout stream. It does not affect or require command line arguments. (Unless, of course, you are actually printing command line arguments...)
  • cdhowie
    cdhowie over 13 years
    For example, on Linux you might ls -l somefile to look at the directory listing for "somefile". This would pass the arguments "-l" and "somefile" to the "ls" program. On Windows, you might "dir somefile" and in that case the singular "somefile" argument would be passed to the "dir" program.
  • Anthony
    Anthony over 13 years
    cdhowie, i understand that printing to the stdout stream is not the same as printing cla's! i understand the whole example you gave on the linux ls command also. i dont know why the concept is so hard for me? Maybe its because i dont know why CLA are used???
  • cdhowie
    cdhowie over 13 years
    Have you ever used a command-line driven OS, like DOS or Linux? If not, that might be why you don't understand why they are used. In a command-line environment, command-line arguments are the primary tool you have to tell programs what you want them to do.
  • Anthony
    Anthony over 13 years
    i use Linux! I work with NMAP all the time! Im always on the terminal!
  • Anthony
    Anthony over 13 years
    can you give me a working example of printing a file to stdout using CLA?
  • cdhowie
    cdhowie over 13 years
    Well, a complete example probably wouldn't fit here, but I will say that if your program wants to accept one argument and then dump the contents of that file to stdout, you could start with something like this, assuming you are writing this inside the main function, as defined above: if (argc != 2) { /* Need one argument */ printf("Usage: %s filename\n", argv[0]); return 1; } int fd = open(argv[1], O_RDONLY); ...
  • Anthony
    Anthony over 13 years
    idk man i understand all that i know if i type Nmap -SP 192.168.100.57-250 nmap is argv[0] the name of the program. and anything after is indiced consecutively. i just dont understand how to program with them. idk y! I would really like to learn but i am having this problem for some reason.
  • cdhowie
    cdhowie over 13 years
    If you understand how they are transferred, but not how to parse them, I suggest reading Toby's answer below.
  • Anthony
    Anthony over 13 years
    Let me hit the books, Google, and Toby's link. If I am still having problems Cdhowie, I will come back. Hopefully that will not be the case!
  • dmckee --- ex-moderator kitten
    dmckee --- ex-moderator kitten over 13 years
    NB: While argv[0] is supposed to be the name of the program as invoked the exec family of functions on unix makes it possible this condition to be broken.
  • Siamore
    Siamore over 13 years
    @antony i know it can be frustrating to not be able to comment with low rep but you should have just asked another question or looked up other questions which are similar, as for your question you shouldn't name your executable as cp but anyway its easier to compile from the command line use this command on your c file after using cd to make the directory it is in using cd, gcc -o "name of executable" yourFile.c and then run it using ./"name of executable" thats it!
  • Keith Thompson
    Keith Thompson almost 11 years
    main is called from the cathode ray tube? You might want to update your answer to say that CRT means "C runtime".
  • Keith Thompson
    Keith Thompson almost 11 years
    int main(void) is also a valid declaration for main, useful if you want to ignore any command-line arguments.