Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Command line argument

  1. Aug 3, 2004 #1

    Math Is Hard

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    I am looking at a sample program in my C programming book that demonstrates using standard I/O to read a file. The program checks to see if there is a command line argument. I am not sure what a command line argument is. I am also not sure how to even run the program. (I think I have to run this from the command prompt after compiling.)
    Let me know if I am not being specific enough and I'll post the example.

    Thanks!
     
  2. jcsd
  3. Aug 3, 2004 #2
    When you run the program from the command prompt, you are typing a command at the prompt. That command is written in the form of a line. After the name of the program on the line, subsquent text can be interpreted as arguments. These arguments typed on the command line are called command line arguments.
     
  4. Aug 3, 2004 #3

    plover

    User Avatar
    Homework Helper

    Suppose at your command prompt (I'll use '>' for a prompt) you type:
    > sort myFile.txt mySortedFile.txt
    where 'sort' is a program that takes the lines from the file named by its first argument (in this case, 'myFile.txt') puts them in alphabetical order then writes them out to a file named for the second argument ('mySortedFile.txt'). In this example, the two file names would be considered 'command line arguments'.

    In C, when you declare main as:
    int main(int argc, char* argv[])
    you are telling the system that you want to know what the command line arguments are.
    • argc stands for 'argument count' and it contains the number of elements in the array argv.
    • argv stands for 'argument vector' and is an array of strings, one string for each space-separated set of characters on the command line.
    Note that the first element of argv is always the name of the program as that is the first word on the command line. Thus argc is always at least 1. (It is possible that the program name might be unavailable for some reason, in which case argc would still be at least 1, and argv[0] would contain an empty string.)

    It is up to the programmer to process these arguments as they see fit. There is often a library included with a given compiler to support whatever the command line conventions are for the OS. E.g. the GNU 'getopt' library handles Unix-style command line arguments. I would not be surprised if there were a similar facility in VC++ for DOS-style command syntax.

    I think there is a way to specify command line arguments for testing purposes in the VC++ project options, but I'm not sure how it's done.

    The names argc and argv are artifacts of the original development of C and Unix. While cryptic, they are a universal convention of C programming -- not using them is very bad juju. If you're found out, some people from the Free Software Foundation will probably sneak into your house at night and shave your cat... :eek:
     
    Last edited: Aug 3, 2004
  5. Aug 3, 2004 #4

    Math Is Hard

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    umm.. ok, let's say my sorting program is called sorting.c. Do I make an executable (sorting.exe)? And then at the command prompt do I run sorting.exe? Then do I enter the arguments (the names of the two text files) at the command prompt? I am not sure if this is the way it's done or if these steps are in the right order. I have never run anything outside of the Visual C++ environment.

    I am very uneasy about this Free Software Association that you speak of, plover. I have reported them to PETA, and I am knitting a little sweater for my cat just to be safe.
     
  6. Aug 3, 2004 #5

    BobG

    User Avatar
    Science Advisor
    Homework Helper

    So this line is for when the program is started from outside the C environment? For example, if you had an old DOS machine, this handles how the program would be started from CLI, right?
     
  7. Aug 3, 2004 #6

    plover

    User Avatar
    Homework Helper

    I'm not precisely sure what you mean by "outside the C environment", but yes, this is the signature for the startup function of a standard C program that can receive parameters at startup. It doesn't matter whether the program is started explicitly from a command line, through some kind of script language, due to a directive from another program, or for reasons internal to the OS.

    The only environment that I'm aware of where any other startup mechanism is used by a C or C++ program is Windows where programs that make use of the Windows GUI use are required to use a function called WinMain (I forget the complete signature) for startup.

    C programs that use a GUI under Unix-style OSes do not have a special signature for startup. They use the standard startup and call an initialization function to connect to the GUI facilities.

    While the command line is much more obvious on an old DOS machine, it still exists in modern Windows. Start->Run provides an interface for a single command line, and it's possible to pull up a full DOS style command shell (Start->Programs->Accessories->Command Prompt). The "Properties" box for a Windows Shortcut allows arguments to be sent to the program. (Also, there are free Unix-style shells and command line tools that run under Windows for those of us whose brains go into meltdown without them... :biggrin: )
     
  8. Aug 3, 2004 #7

    Math Is Hard

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    I asked someone at work about how I could run the sorting program and he said at the command prompt I would want to enter:
    > sorting.exe sort myFile.txt mySortedFile.txt

    Does that look right? I should put in the program name and then the 2 arguments on one line? Thanks.
     
  9. Aug 3, 2004 #8

    plover

    User Avatar
    Homework Helper

    This is the right idea. However, the name of the .c file does necessarily have to have anything to do with the name of the executable (though it is the default for the compiler to name the executable after the file containing "main").

    Terminology nitpick: To a programmer, the name of a source file is not the same thing as the name of a program, as a program can have many source files. So the phrasing "a program called sorting.c" sounds strange. It would be more usual to say: "Let's say my sorting program is defined in the file sorting.c ..." Or even just: "Let's say my sorting program is in sorting.c ..."
    The point of command line arguments is that they can be passed to the program as it starts. The sequence of events that you seems to be describing is: type the name of the program, press RETURN, type the arguments, press RETURN again. However, at a command line, when you press RETURN, the OS assumes that all the information necessary is there on the current command line and starts the program (there are exceptions to this involving ways to end a command line with an indication that you aren't finished yet, but the principle stays the same). Thus it is necessary to include the name of the program and all the arguments on your command line, e.g.
    > sorting.exe input.txt output.txt
    Note that including the ".exe" is not strictly necessary.

    It is important to know that separation between arguments is indicated by spaces, not any kind of punctuation mark like a comma. If you typed:
    > sorting.exe input.txt, output.txt
    The program would look for a file called "input.txt," to work on.

    This means care must be taken with file names containing spaces. To indicate that several space-separated sequences should be treated as one unit, surround them with double-quote marks:
    > sorting.exe "long file name with spaces.txt" output.txt

    Perhaps they could be surprised by leaving them a skunk (outside of course). But if you put the catfood dish outside, it'll be too dark for them to know what's eating out of it until too late...
     
  10. Aug 3, 2004 #9

    plover

    User Avatar
    Homework Helper

    > sorting.exe sort myFile.txt mySortedFile.txt
    If you are following my example from last night, the extra word "sort" is not necessary, but just make it:
    > sorting.exe myFile.txt mySortedFile.txt
    then it would be correct.
     
  11. Aug 3, 2004 #10

    Math Is Hard

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    :redface: sorry, that extra sort must have been a typo. We skunks are somewhat nearsighted. :smile:

    and if I followed you correctly then this would also be acceptable:

    > sorting myFile.txt mySortedFile.txt

    I think?
     
  12. Aug 3, 2004 #11

    Math Is Hard

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    hehehehehehe <snort>
     
  13. Aug 3, 2004 #12

    plover

    User Avatar
    Homework Helper

    Plus, they refuse to make keyboards for skunk size fingers... (has PETA been informed of this?) :biggrin:

    Looks good to me... :smile:
     
  14. Aug 4, 2004 #13

    Math Is Hard

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    Thanks for your help, plover. I actually have a tiny little ergonomic skunk keyboard that I use. I had it custom made for me. I am hoping to also get a mouse made this year - the one I have now is too big and I have to push around with my nose. :biggrin:

    BTW, have you ever seen a skunk's feet? They look just like little tiny hands!
     
  15. Aug 8, 2004 #14

    Math Is Hard

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    control loop problem - I think..?

    I am working on a program that allows me to enter names of text files as command line arguments and then sequentially displays the name of the file
    and the file's contents. I've got a little loop problem with displaying the contents of anything after the first file though.
    For instance if I enter at the command line
    > display.exe FileA.txt File B.txt
    It will print
    FileA.txt These are the contents of FileA FileB.txt (null)

    Maybe I am just tired and not seeing something obvious. :yuck: If someone could take a look I'd appreciate it. Many thanks! :smile:

    PHP:

    #include <stdio.h>
    #include <stdlib.h>

    int main(int argc, char *argv[])
    {
      int ch;
      FILE * fp;
      int i;
     
      if (argc < 2) //if no filename entered
      {
        printf("Usage: %s filename\n", argv[0]);
        exit(1);
      }
      if ((fp = fopen(argv[1], "r")) == NULL)   //can't open file
      {
        printf ("Can't open %s \n", argv[1]);
        exit(1);
      }

      for (i=1; i< (argc+1); i++)
      {
        printf("%s ",argv[i]);  // print filename
        while ((ch = getc(fp)) != EOF) 
        {
          putc(ch, stdout); //print contents of file
        }
      }

      return 0;
    }
     
     
       
     
     
  16. Aug 8, 2004 #15

    plover

    User Avatar
    Homework Helper

    As it stands, only the first file is ever opened. After printing the contents of the file, you need to close the current file object, then open a new one for the next file.
     
  17. Aug 8, 2004 #16

    Math Is Hard

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    aw crud! I think I am seeing it now.
    I started by trying to just open and display one file and then tried to modify that.
    thanks, plover!
     
  18. Aug 8, 2004 #17

    Math Is Hard

    User Avatar
    Staff Emeritus
    Science Advisor
    Gold Member

    WEE-hoooOOoooo! Got it working!!!! (doing my happy dance now)
    Thanks again. :biggrin:
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?