C Programming: Understanding Command Line Argument

In summary, the conversation discusses a sample program in a C programming book that uses standard I/O to read a file and checks for a command line argument. The concept of command line arguments is explained, along with the purpose of the argc and argv parameters in the main function. The process of running the program from the command prompt is also discussed. The conversation also mentions the use of a library to handle command line arguments and the potential consequences of not using the correct conventions in C programming.
  • #1
Math Is Hard
Staff Emeritus
Science Advisor
Gold Member
4,652
37
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!
 
Computer science news on Phys.org
  • #2
Math Is Hard said:
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!

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.
 
  • #3
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:
  • #4
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.
 
  • #5
In C, when you declare main as:
int main(int argc, char* argv[])

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?
 
  • #6
BobG said:
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?
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: )
 
  • #7
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.
 
  • #8
Math Is Hard said:
umm.. ok, let's say my sorting program is called sorting.c. Do I make an executable (sorting.exe)?
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 ..."
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.
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

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.
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...
 
  • #9
Math Is Hard said:
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.

> 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.
 
  • #10
plover said:
> 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.

: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?
 
  • #11
plover said:
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...

hehehehehehe <snort>
 
  • #12
Math Is Hard said:
:redface: sorry, that extra sort must have been a typo. We skunks are somewhat nearsighted. :smile:
Plus, they refuse to make keyboards for skunk size fingers... (has PETA been informed of this?) :biggrin:

> sorting myFile.txt mySortedFile.txt
Looks good to me... :smile:
 
  • #13
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!
 
  • #14
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;
}
 
  • #15
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.
 
  • #16
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!
 
  • #17
WEE-hoooOOoooo! Got it working! (doing my happy dance now)
Thanks again. :biggrin:
 

1. What is C Programming?

C Programming is a high-level programming language commonly used for system programming and creating operating systems. It was developed in the early 1970s by Dennis Ritchie at Bell Labs.

2. What are Command Line Arguments in C Programming?

Command Line Arguments are inputs given to a C program through the command line when it is executed. They allow the user to provide data or settings to the program at runtime.

3. How do I use Command Line Arguments in my C program?

To use Command Line Arguments in a C program, you need to include the "stdio.h" header file and add the "main" function with two arguments: argc and argv. The "argc" argument represents the number of arguments entered, and the "argv" argument is an array of strings containing the arguments.

4. What is the purpose of using Command Line Arguments in a C program?

The main purpose of using Command Line Arguments in a C program is to provide the program with external inputs and make it more flexible. This allows the user to customize the program's behavior without changing the actual code.

5. Can I pass multiple Command Line Arguments to my C program?

Yes, you can pass multiple Command Line Arguments to your C program. Each argument is separated by a space when entered in the command line. The program can then access each argument through the "argv" array using its index.

Similar threads

  • Computing and Technology
Replies
6
Views
1K
  • Computing and Technology
Replies
3
Views
1K
  • Programming and Computer Science
Replies
5
Views
1K
  • Programming and Computer Science
Replies
14
Views
2K
Replies
16
Views
2K
  • MATLAB, Maple, Mathematica, LaTeX
Replies
9
Views
2K
  • Computing and Technology
Replies
20
Views
695
  • Programming and Computer Science
Replies
12
Views
9K
Replies
6
Views
6K
  • Computing and Technology
Replies
2
Views
3K
Back
Top