How can i do this, Command Line Arguments in c - c

I am learning C, and I am in the part about the arguments: int argc, char *argv[].
I am trying to make a code that prints a result according to the argument put in console. For example:
./a.out -E
to print "Hello World!"
./a.out -S
to print "Hello World in Spanish"
I have the following code, but I still don't know how to get it.
int main(int argc, char *argv[]) {
if(argc == 1){
printf("Hello World!");
}
else if(argc > 2){
printf("Too many arguments supplied.\n");
}
else if(argv[2] == '-S'){
printf("Hola Mundo in Spanish"); //show errors
}
else {
printf("Hello, %s!!\n", argv[1]);
}
return EXIT_SUCCESS;
}

Array indexing in C is zero-based. If argc is 2, then argv[0] is the path to your executable, and argv[1] is the first argument.
The other problem you have is you cannot compare char* strings with ==, and you cannot have a single character '-S'. Yes, single-quotes is for a character, and double-quotes is for a string.
Use strcmp() from <string.h> as follows:
if (strcmp(argv[1], "-S") == 0) {
printf("Hola Mundo in Spanish\n");
}

Related

Compare command line arguments to string in C?

Compare command line arguments to strings in c?
for example I want just the word "autoplay" to be the command line argument, how can i validate that this is the only word? i already have it validating for more than 1 word.
if( argc == 2 ) {
autoplay(num5);
}
You use strcmp() to compare strings; note it returns 0 on match. If you want it case insensitive then you need to use strcasecmp() instead:
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv) {
if(argc == 2 && !strcmp(argv[1], "autoplay")) {
printf("match\n");
// autoplay(num5);
return 0;
}
printf("no match\n");
}
and example run;
./a.out
no match
./a.out autoplay
match

How to solve segmentation fault in c?

When I was making my program I got an error type of thing called Segmentation Fault.
#include <cs50.h>
#include <string.h>
#include <stdio.h>
int main(int argc, string argv[])
{
char i = strlen(argv[2]);
if (argc == 2)
{
printf("%i %s %hhd", argc, argv[2], i);
}
}
I run this program using these commands
make substitution
and then
./substitution abcdefghijklmnopqrstuvwxyz
In this we have to add a 26 word key which in the above line is a to z.
Please help if you know to solve
If you invoke your program with:
./substitution abcdefghijklmnopqrstuvwxyz
argc will be 2, and argv will be an array of 3 pointers:
argv[0] points to the string ./substitution, argv[1] points to the string abcdefghijklmnopqrstuvwxyz, and argv[2] is NULL. If you attempt to compute the length of NULL by calling strlen(argv[2]), that is an error. You must not pass NULL to strlen. I think your error is simply mis-indexing the argv array. Arrays in C are zero based. If you want to compute the length of the first argument, you want to work with argv[1], not argv[2]:
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int
main(int argc, char *argv[])
{
int rc = EXIT_FAILURE;
if( argc > 1 ){
size_t i = strlen(argv[1]);
printf("%i %s %zd\n", argc, argv[1], i);
rc = EXIT_SUCCESS;
}
return rc;
}
You got hit with segfault because the number of required arguments specified was done poorly. The main problem is here:
if (argc == 2)
The number of actual arguments passed by the user is equal to the number of required arguments minus 11. It should be:
int main(int argc, char *argv[]) {
if (argc != 3) {
// Number of arguments are either greater or lesser than 3
// Handle the error
}
// Ok...
}
You can safely use the arguments now.
1. The calling command for the program, for example ./a.out is also counted as an argument (argv[0]).

How to determine the value of the argument entered in the terminal using C language [duplicate]

This question already has answers here:
How do I properly compare strings in C?
(10 answers)
Closed 2 years ago.
I would like to write a program that performs different function based on the argument provided.
For example:
$ ./program -a //line 1
$ ./program -b //line 2
if I enter line 1 in terminal, I want it to print "Hi"
if I enter line 2 in terminal, I want it to print "Bye"
Here is my current logic, which does not work in C:
int main (int argc, char *argv[])
{
if (argv[1] == "-a"){
printf("Hi");
} else if (argv[1] == "-b")
{
printf("Bye");
}
Can anyone help me fix my code in order to achieve my objective?
Thanks in advance!
You should use strcmp() to compare strings in C.
#include <stdio.h>
#include <string.h> /* for strcmp() */
int main (int argc, char *argv[])
{
if (strcmp(argv[1], "-a") == 0){
printf("Hi");
} else if (strcmp(argv[1], "-b") == 0)
{
printf("Bye");
}
return 0;
}

Comparing C strings vs. string pointers for equality

So I am working on a project to create and use a shell. One thing that must be done is "|executable| -p |prompt| should allow the user to select an user-defined prompt. Otherwise, the default should be “257sh> ”. I wrote my code to do this however no matter what it keeps moving into the else statement. After some experimenting I know that my argv[1] == "-p" line is what is causing the issue, because without it the code works. The thing is that when I print out argv[1], it prints "-p" (assuming thats what I input). Here is my shell function.
void shellLoop(char *n)
{
char *line;
char **args;
int status;
char name = n;
do{
printf("%s>", n);
line = sysReadLine();
args = splitLine(line);
status = execute(args);
free(line);
free(args);
}while(status);
}
And here is my main function
int main(int argc, char *argv[])
{
if(argc == 3 && argv[1] == "-p"){
shellLoop(argv[2]);
}
else{
shellLoop("257sh");
}
return EXIT_SUCCESS;
}
When you do argv[1] == "-p" you compare two pointers, and two pointers that will never be the same.
To compare strings in C you use the strcmp function: strcmp(argv[1], "-p") == 0.
You can also use strncmp(char *str1,char *str2,int n) to compare the first n bytes of two strings.

C program with command line options

I wonder how to write a C program with options that can be invoked by a terminal.
Example : Person.c
#include <stdio.h>
void main ()
{
char option;
if(option == 'f') printf("First Name");
else if(option == 'l') printf("Last Name");
else printf("Full Name");
}
Compile it with
cc Person.c -o Person
Objective :
I want to reach my program options through terminal.
Example :
./Person -f
Output : First Name
void main () is wrong, if you copied this from a book, throw the book away
It should be int main(int argc, char **argv), argc will then be set to the number of arguments and argv[1] .... argv[argc-1] are the argument strings (argv[0] is the name of the program)
Here's my $0.02:
#include <stdio.h>
#include <string.h>
int
main (int argc, char *argv[])
{
if (argc != 2) {
printf ("USAGE: ./Person [-f|-l]\n");
return 1;
}
if (strcmp (argv[1], "-f") == 0) {
printf("First Name");
}
else if (strcmp (argv[1], "-l") == 0)
printf("Last Name");
}
else {
printf ("Unknown argument\n");
return 1;
}
return 0;
}
Important points:
1) In C, you can't just compare strings (like "aaa" == "bbb"). You need special library functions, like "strcmp()" ("compare strings").
2) In order to use library functions, you need to #include headers (like "stdio.h", for "printf()", or "string.h", for "strcmp()"). You can find out which headers you need by using "man" ... or simply Googling for the relevant call ("google strcmp" should give you the same results as "man strcmp")
3) It's a good general convention to use the programs return values to indicate "success" or "failure". "0", by convention, usually means "success".
4) Finally, for your purposes, it's essential to use "argc" and "argv" to access your command line arguments.
5) The "if (argc != 2)" at the top insures that you've entered at least one command line argument (argument "0" is the name of the program itself). This is important because trying to read an argument you don't have ("trying to read off the end of the array") could cause a crash ;)
'Hope that helps!
Please change your main prototype as
int main(int argc, char *argv[])
The options as asked by you in your question can be passed using the input arguments to the main function as given above.
The argc parameter tells you how many inputs has been passed through terminal and the argv will provide you each input as an array of char *. Please note that the first input (argv[0]) will be by default the filename of the executable with full path and the rest of inputs will follow it.
http://www.cprogramming.com/tutorial/c/lesson14.html - This tutorial will also be of some help.
The correct form for a main function is:
int main(int argc, char **argv) {
}
Then argv holds your command line arguments:
int main(int argc, char **argv) {
for(int i = 0; i < argc; ++i) {
printf("arg %d is %s", i, argv[i]);
}
return 0; // indicates that the program completed successfully
}
Call main with these inputs:
int main ( int argc, char **argv)
argc is the number of args, and argv is an array of the command line arguments. Note that the first argument of argv is the program name.
you have to tell C that your giving it options
int main(int argc, char **argv)
argc is the number of arguments and argv is the argument you call
so then ./Person -f
you need to tell it
if (strncmp(argv[i],"-f",1) == 0) {
You should also look at some of the parsing libraries out there. Many people have written great libraries for parsing command line options so that you don't have to repeat all of the work of validating options. Most are pretty easy to use, as well.

Resources