Skip to main content

Command-line Arguments in C

Command-line arguments are a way to pass information or inputs to a C program when you run it from the command line or terminal. These arguments provide additional flexibility and let users control the program's behavior without changing the code.

In C, command-line arguments are handled through the main function, which takes two parameters:

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

Here’s what these parameters mean:

  1. argc (Argument Count): This integer represents the number of command-line arguments, including the program name.
  2. argv (Argument Vector): This array of strings (char *argv[]) holds each command-line argument as a string. argv[0] is always the program's name, and the remaining elements are the actual arguments passed by the user.

Example: Printing Command-Line Arguments

Let’s start with a basic example where we simply print all command-line arguments.

#include <stdio.h>

int main(int argc, char *argv[]) {
    printf("Number of arguments: %d\n", argc);
    
    for (int i = 0; i < argc; i++) {
        printf("Argument %d: %s\n", i, argv[i]);
    }

    return 0;
}

Explanation:

  1. Printing Argument Countargc gives the count of arguments, which we print.
  2. Printing Each Argument: We loop through argv, printing each argument. argv[0] is the program's name, and argv[1]argv[2], etc., are the arguments provided by the user.

Running the Program

If we compile this program as example, we could run it with arguments like this:

./example hello world 123

Expected Output:

Number of arguments: 4
Argument 0: ./example
Argument 1: hello
Argument 2: world
Argument 3: 123

Important Points

  1. Data Type: Command-line arguments are passed as strings, so you may need to convert them (e.g., atoiatof).
  2. Error Handling: Always check if the right number of arguments is provided to avoid errors.
  3. Applications: Command-line arguments are useful for tasks like specifying filenames, setting configuration options, or providing user inputs.

Command-line arguments give users control and make programs more versatile.


Sample Program to add two numbers passed as command line arguments
#include <stdio.h>
#include <stdlib.h>
int main(int argc,char *argv[])
{
 if(argc!=3)
  {printf("Invalid number of arguments...\n");
   exit(0);
  }
else
  {
  printf("Sum=%d",atoi(argv[1])+atoi(argv[2]));
  }
}
Note:if the default executable is used then use ./a.out 2 3 for adding two numbers
The function atoi() will convert string to integer

Program to display contents of several  files passed as arguments.
#include <stdio.h>
#include <stdlib.h>
int main(int argc,char *argv[])
{
int i=1
int c;
int nargs=0;
FILE *fp;
If(argc==1)
{
printf(“No input file to display);
exit(1);
}
nargs=argc-1;
while(nargs>0)
{
nargs--;
printf(“Displaying the  content of file %s”,argv[i]);
p=fopen(argv[i],”r”);
if(fp==NULL)
{
printf(“cannot open file %s”,argv[i]);
continue;
}
c=getc(fp);
 while(c!=EOF)
 {
 putchar(c);
 c=getc(fp);
 }
fclose(fp);
printf(“\n\n************end of file %s\n\n”,argv[i]);
i++;

}
return 0;
}

Simulation of copy command where the two file names are passed as arguments
#include <stdio.h>
#include <stdlib.h>
int main(int argc,char *argv[])
{
FILE *in,*out;
int c;
if (argc !=3)
{
printf(“Invalid number of arguments”);
exit(0);
}
in=fopen(argv[1],”r”);
if(in==NULL)
{
printf(“couldn’t open the source file..”);
return 0;
}
out=fopen(argv[2],”w”);
if(out==NULL)
{
printf(“couldn’t open the destination file..”);
return 0;
}
while(!feof(in))
{
c=fgetc(in);
if(!feof(in))
 fputc(c,out);
}
fclose(in);
fclose(out);
return 0;
}


Comments

  1. Keep sharing such a useful information..!! Great blog. Computer programming courses

    ReplyDelete
  2. I have read all your articles. I wonder why you can write them. They are easy to understand and accessible. They help me much too. I'm thankful if you can upload more posts later. Thanks for your sharing.
    Hướng dẫn đăng ký B30 VinaPhone, Đăng ký Mimax sinh viên VinaPhone, Đăng ký Mimax50 VinaPhone, Đăng ký 3G VinaPhone 1 ngày chỉ 5K,7K,10K

    ReplyDelete
  3. recent sales notification popup 2018
    pop sales
    Say, you got a nice post.Much thanks again. Really Cool

    ReplyDelete
  4. For space outside the milk tea shop closer to nature, outdoor space should use speakers with greater capacity, products such as garden speakers, imitation stone speakers, are products with designs The most natural to create interesting feeling when enjoying. Because it must work in the weather conditions heat so the shell is made very firmly with high durability, the quality of the speaker is imported genuine. Good sound, making good clear sound even when used in wide space
    Gái gọi Mỹ Đình - Đình Thôn, gái gọi Nguyễn Khánh Toàn, gái gọi hà nội, gái gọi Phố Cổ - Quán Sứ

    ReplyDelete

Post a Comment

Popular posts from this blog

KTU Mandatory C programs for Laboratory and Solutions

LIST OF LAB EXPERIMENTS 1. Familiarization of Hardware Components of a Computer 2. Familiarization of Linux environment – Programming in C with Linux 3. Familiarization of console I/O and operators in C     i) Display “Hello World”     ii) Read two numbers, add them and display their sum     iii) Read the radius of a circle, calculate its area and display it 4. Evaluate the arithmetic expression ((a -b / c * d + e) * (f +g))   and display its solution. Read the values of the variables from the user through console 5. Read 3 integer values, find the largest among them. 6. Read a Natural Number and check whether the number is prime or not 7. Read a Natural Number and check whether the number is Armstrong or not 8. Read n integers, store them in an array and find their sum and average 9. Read n integers, store them in an array and search for an element in the    array using an algorithm for Linear Search 10.Read n integers, store them in an array and sort the elements in t

PROGRAMMING IN C KTU EST 102 THEORY AND LAB NOTES

PROGRAMMING IN C  KTU  EST 102  THEORY AND LAB   COMMON FOR ALL BRANCHES About Me Syllabus Theory Syllabus Lab Model Question Paper EST 102 Programmin in C University Question Papers  and evaluation scheme   EST 102 Programming in C  Introduction( Lab) Introduction to C programming Linux History and GNU How to create a bootable ubuntu USB stick Installing  Linux Install Linux within  Windows Virtual Box and WSL Linux Basic Features and Architecture Basic Linux Commands Beginning C Programming Compiling C programs using gcc in Linux Debugging C program using gdb Module 1: Basics of computer hardware and software          Module-1 Reading Material Basics of Computer Architecture Hardware and Software System Software and Application Software  Programming Languages ( High level, Low level and Machine Language) and Translators ( Compiler, Interpreter, Assembler) Algorithm, Flowcharts and Pseudo code Program Development Structured Programming Basics of hardware ( video) Know about Motherboar