Command-Line Arguments in C




Command-Line Arguments in C




Table of Contents





Introduction to Command-Line Arguments


When you run a C program from the command line, you can pass additional information to the program using command-line arguments. These arguments are provided after the program name and are separated by spaces. They are accessible within the main function using parameters argc and argv.


argc: Stands for "argument count" and represents the number of command-line arguments.


argv: Stands for "argument vector" and is an array of strings that contains the actual arguments.




Accessing Command-Line Arguments


Let's see how to access and print the command-line arguments using a simple program:



#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;
}



Example: Sum of Integers


Now, let's create a program that calculates the sum of integers passed as command-line arguments:



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

int main(int argc, char *argv[]) {
if (argc < 2) {
printf("Usage: %s <num1> <num2> ...\n", argv[0]);
return 1;
}

int sum = 0;
for (int i = 1; i < argc; i++) {
sum += atoi(argv[i]);
}

printf("Sum: %d\n", sum);

return 0;
}



Example: File Copy Utility


Here's an example of a simple file copy utility using command-line arguments:



#include <stdio.h>

int main(int argc, char *argv[]) {
if (argc != 3) {
printf("Usage: %s <source_file> <destination_file>\n", argv[0]);
return 1;
}

FILE *source = fopen(argv[1], "rb");
FILE *destination = fopen(argv[2], "wb");

if (!source || !destination) {
printf("Error opening files.\n");
return 2;
}

int ch;
while ((ch = fgetc(source)) != EOF) {
fputc(ch, destination);
}

fclose(source);
fclose(destination);

printf("File copied successfully.\n");

return 0;
}



Conclusion


Command-line arguments are a valuable tool in C programming for interacting with your programs in a more dynamic way. They allow you to provide input and configuration without modifying your source code. By using the argc and argv parameters, you can create versatile and interactive applications.


In this post, we covered the basics of command-line arguments, how to access them, and provided practical examples to help you grasp their usage. Experiment with these examples and explore further to unlock the full potential of command-line arguments in your C programs. Happy coding!





Post a Comment

0 Comments