Command line arguments in C

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.
They provide flexibility and let users control the program’s behavior without changing the code.


Syntax in C

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

Parameters

  • argc (Argument Count)

    • Integer representing the number of command-line arguments

    • Includes the program name

  • argv (Argument Vector)

    • Array of strings containing the arguments

    • argv[0] → program name

    • argv[1], argv[2], ... → user arguments


Example 1: Printing 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; }

Running the Program

./example hello world 123

Expected Output

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

Important Points

  • Data Type: Arguments are passed as strings

  • Conversion: Use functions like atoi(), atof() to convert values

  • Error Handling: Always check argument count

  • Applications:

    • Passing filenames

    • Configuration settings

    • User inputs


Example 2: Add Two Numbers Using 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])); } }

Run

./a.out 2 3

Note: atoi() converts string to integer.


Example 3: Display Contents of 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\n", argv[i]); fp = fopen(argv[i], "r"); if(fp == NULL) { printf("Cannot open file %s\n", argv[i]); 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; }

Example 4: Simulation of Copy Command

(Copy contents from one file to another)

#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

Popular posts from this blog

Programming in C GXEST204 - KTU 2024 scheme syllabus notes pdf ------- Dr Binu V P

Structure of a C Program

Single and Multi Dimensional Arrays