How to pass command line arguements to my main function? [duplicate] - c

This question already has answers here:
What does int argc, char *argv[] mean?
(12 answers)
Closed 9 years ago.
So my main function looks like this:
int main(int numberOfArguments, char* argumentArray[]) {
if (assemble(numberOfArguments, argumentArray)) {
return 0;
} else {
return -1;
}
}
I want to be able to give to the command line the arguement
./program inputFile.txt outputFile.txt // PROBLEM IS that this is being interpreted as 3 command line arguments somehow when it is only 2.
where inputFile.txt is argumentArray[0] and outputFile.txt is argumentArray[1]

The generation of arguments from the text command line is platform-specific, but the first element of the argv array is almost always the name used to find your program.
If you want to discard this first argument, simply add to the beginning of main:
-- numberOfArguments;
++ argumentArray;

every word you type into the command line (beginning with the executable name) is passed to the main function at begin. related question
The first argument argumentArray[0] is the as readable in the realted question reserved.
After that you get each word (seperated by whitespaces in the commandline) as an element in the argumentArray.
The size of the argumentArray is given by numberOfArguments.
So if you insist on having your input file on [0] you should work with some pointer arithmetics like argumentArray++; otherwise you have the given data at [1] and [2] automatically.

Related

Command line argument condition pset2 caesar

I'm just started with a course for learning C, and am bumping in a problem with command line arguments. The assignment is this (there is more, but this is the part about the command line argument at the start):
- Your program must accept a single command-line argument, a non-negative integer.
- If your program is executed without any command-line arguments or with more than one command-line argument, your program should print an error message of your choice and return 1.
- You can assume that, if a user does provide a command-line argument, it will be a non-negative integer (e.g., 1). No need to check that it’s indeed numeric.
So I came up with this code:
#include <stdio.h>
#include <cs50.h>
#include <string.h>
int main(int key, string plain[]) {
if (key < 0 || plain[key] > 1)
{
printf("error\n");
return 1;
}
else
etc...code continues.
Now I've tried several things, but I'm running into a wall.The compiler doesn't want to accept the if-condition I came up with, saying there is an error with comparison between pointer and integer which refers to the bold condition on the list of the assignment. So I understood that the argv part of the command line argument is the array of strings that the user put in. So my thought was to tell the compiler that when the user gives more than one string it should give an error message, so I wrote "plain[key] > 1)". Or is my understanding of command line arguments completely off here? Thanks.
plain[key] access the key element of plain array of string pointers (argv).
The size of that array is expressed by key (argc).
So what you want is
if (key > 1)
{
//..
}
Moreover plain last element is key-1, 'cause is 0 based index.
You misunderstood the purpose of the arguments to main. The first int argument (usually named argc) is the number of items in the array argument.
And the array argument (usually called argv) contains all the arguments to your program (including the executable name) as text.
So if your executable is called foo, and you invoked it as foo 1 a bar, the arguments to main will be as follows:
int argc == 4
char **argv => {"foo", "1", "a", "bar"}
So if your program must accept a single argument, it must hold that argc == 2 and argv[1] is the argument, that you must convert to a number from a string.

How to pass this array of c strings correctly [duplicate]

This question already has answers here:
How do I pass this array of c strings correctly? [closed]
(3 answers)
Closed 9 years ago.
I already asked this question and did a very poor job posting it leading to confusing answers that did not help me solve my problem whatsoever. This time ill be trying harder to make my question easier to address. Here is the problem below...
int builtin_cmd(char **argv);
int main()
{
char *argv[128]; //create an array of c_strings with 128 slots in the array
//put 'quit' into argv[0].. (This was done by another file given to me by the professor)
printf("%s\n", argv[0]); //prints 'quit', as it should
builtin_cmd(argv); //call builtin_cmd and pass argv to the function
}
int builtin_cmd(char **argv)
{
printf("%s\n", argv[0]); //prints nothing, should have printed 'quit'
}
Basically the issue that I am having is accessing char *argv[128] in the function builtin_cmd. I set the first index in the array to the c_string 'quit' and print it right there and it works just as I expected it too the printf() prints out 'quit' in the terminal. However, once I call builtin_cmd(argv); the line printf("%s\n", argv[0]); prints absolutely nothing as if the argv was empty. How am i supposed to correctly pass argv into the function builtin_cmd?
It should work well except you forget to return values in builtin_cmd() and main(). Check out running result on Ideone .

Incorrect command line arguments number when passing `*` [duplicate]

This question already has answers here:
The issue of * in Command line argument
(6 answers)
Closed 3 years ago.
I'm writing a C program about Reverse Polish Notation, which takes its operands and operators through the command line arguments. But things go wrong when the multiply operator '*' occurs, and I don't know why.
Here is the little program to debug.
test.c
int main(int argc, char **argv)
{
printf("%d\n", argc);
return 0;
}
// run case result
./test a b 3
./test * 66
So why the '*' argument makes a wrong result ?
The * does a shell glob. So it'll expand to all the files in your current directory, which will be the arguments to your program, you have 65 files in your directory. You can see what's happening if you run echo *
You need to single quote the * as in ./test '*' (double quotes would work too) , this will prevent the shell expanding *. A * is given to your program in this case, the shell removes the single quotes.
If you want to evaluate expressions, you could do
./test 3 2 '*'
In this case your program receives 3 additional arguments separated so argv[1] is 3, argv[2] is 2 and argv[3] is *
Or you could do:
./test '3 2 *'
In this case, your program receives 1 additional argument, argv[1] will be the string 3 2 *
Your command shell is treating * as a wildcard. It's probably including every file in the current directory: 60ish in your case.

C-programming board game [duplicate]

This question already has answers here:
How to parse integer command line arguments in C?
(8 answers)
Closed 9 years ago.
I am trying to make a board game with Maximum board width 80 cells and Maximum board height 52 cells, however the user should be able to choose the dimensions by entering them into the command line, so the dimensions could be smaller than the maximum. I am new to programming but i know that command line arguments are passed through the main function in C, I've just been stuck on this and cant seem to find any answers.
Can anyone help
thank you.
The main function takes two arguments, an integer usually called argc and an array of string pointers usually called argv. main is so usually declared as:
int main(int argc, char *argv[])
The argc variable is the number of arguments passed to your program.
The argv variable is contains the actual arguments pass to your program.
The argc variable is at least equal to 1, as the actual program name is always passed as an argument, and is in argv[0].
If you want two arguments, then you first have to make sure that argc is at least equal to 3. The first argument to your program is then stored as a string in argv[1], and the second is in argv[2].
I recommend you experiment with a program such as this:
#include <stdio.h>
int main(int argc, char *argv[])
{
printf("argc = %d\n", argc);
for (int i = 0; i < argc; i++)
printf("argv[%d] = \"%s\"\n", i, argv[i]);
return 0;
}
And finally (and unrelated to your problem but interesting none the less) is the fact that the size of the argv array is actually one larger than most people expect. The size of the argv array is actually argc + 1 and so can be indexed from argv[0] (the program name) to argv[argc]. This last entry (argv[argc]) is always a NULL pointer.

Arguments to main in C [duplicate]

This question already has answers here:
Pass arguments into C program from command line
(6 answers)
Closed 6 years ago.
I don't know what to do! I have a great understanding of C basics. Structures, file IO, strings, etc. Everything but CLA. For some reason I cant grasp the concept. Any suggestions, help, or advice. PS I am a linux user
The signature of main is:
int main(int argc, char **argv);
argc refers to the number of command line arguments passed in, which includes the actual name of the program, as invoked by the user. argv contains the actual arguments, starting with index 1. Index 0 is the program name.
So, if you ran your program like this:
./program hello world
Then:
argc would be 3.
argv[0] would be "./program".
argv[1] would be "hello".
argv[2] would be "world".
Imagine it this way
*main() is also a function which is called by something else (like another FunctioN)
*the arguments to it is decided by the FunctioN
*the second argument is an array of strings
*the first argument is a number representing the number of strings
*do something with the strings
Maybe a example program woluld help.
int main(int argc,char *argv[])
{
printf("you entered in reverse order:\n");
while(argc--)
{
printf("%s\n",argv[argc]);
}
return 0;
}
it just prints everything you enter as args in reverse order but YOU should make new programs that do something more useful.
compile it (as say hello) run it from the terminal with the arguments like
./hello am i here
then try to modify it so that it tries to check if two strings are reverses of each other or not then you will need to check if argc parameter is exactly three if anything else print an error
if(argc!=3)/*3 because even the executables name string is on argc*/
{
printf("unexpected number of arguments\n");
return -1;
}
then check if argv[2] is the reverse of argv[1]
and print the result
./hello asdf fdsa
should output
they are exact reverses of each other
the best example is a file copy program try it it's like cp
cp file1 file2
cp is the first argument (argv[0] not argv[1]) and mostly you should ignore the first argument unless you need to reference or something
if you made the cp program you understood the main args really...
For parsing command line arguments on posix systems, the standard is to use the getopt() family of library routines to handle command line arguments.
A good reference is the GNU getopt manual
Siamore, I keep seeing everyone using the command line to compile programs. I use x11 terminal from ide via code::blocks, a gnu gcc compiler on my linux box. I have never compiled a program from command line. So Siamore, if I want the programs name to be cp, do I initialize argv[0]="cp"; Cp being a string literal. And anything going to stdout goes on the command line??? The example you gave me Siamore I understood! Even though the string you entered was a few words long, it was still only one arg. Because it was encased in double quotations. So arg[0], the prog name, is actually your string literal with a new line character?? So I understand why you use if(argc!=3) print error. Because the prog name = argv[0] and there are 2 more args after that, and anymore an error has occured. What other reason would I use that? I really think that my lack of understanding about how to compile from the command line or terminal is my reason for lack understanding in this area!! Siamore, you have helped me understand cla's much better! Still don't fully understand but I am not oblivious to the concept. I'm gonna learn to compile from the terminal then re-read what you wrote. I bet, then I will fully understand! With a little more help from you lol
<>
Code that I have not written myself, but from my book.
#include <stdio.h>
int main(int argc, char *argv[])
{
int i;
printf("The following arguments were passed to main(): ");
for(i=1; i<argc; i++) printf("%s ", argv[i]);
printf("\n");
return 0;
}
This is the output:
anthony#anthony:~\Documents/C_Programming/CLA$ ./CLA hey man
The follow arguments were passed to main(): hey man
anthony#anthony:~\Documents/C_Programming/CLA$ ./CLA hi how are you doing?
The follow arguments were passed to main(): hi how are you doing?
So argv is a table of string literals, and argc is the number of them. Now argv[0] is
the name of the program. So if I type ./CLA to run the program ./CLA is argv[0]. The above
program sets the command line to take an infinite amount of arguments. I can set them to
only take 3 or 4 if I wanted. Like one or your examples showed, Siamore... if(argc!=3) printf("Some error goes here");
Thank you Siamore, couldn't have done it without you! thanks to the rest of the post for their time and effort also!
PS in case there is a problem like this in the future...you never know lol the problem was because I was using the IDE
AKA Code::Blocks. If I were to run that program above it would print the path/directory of the program. Example: ~/Documents/C/CLA.c it has to be ran from the terminal and compiled using the command line. gcc -o CLA main.c and you must be in the directory of the file.
Main is just like any other function and argc and argv are just like any other function arguments, the difference is that main is called from C Runtime and it passes the argument to main, But C Runtime is defined in c library and you cannot modify it, So if we do execute program on shell or through some IDE, we need a mechanism to pass the argument to main function so that your main function can behave differently on the runtime depending on your parameters. The parameters are argc , which gives the number of arguments and argv which is pointer to array of pointers, which holds the value as strings, this way you can pass any number of arguments without restricting it, it's the other way of implementing var args.
Had made just a small change to #anthony code so we can get nicely formatted output with argument numbers and values. Somehow easier to read on output when you have multiple arguments:
#include <stdio.h>
int main(int argc, char *argv[])
{
printf("The following arguments were passed to main():\n");
printf("argnum \t value \n");
for (int i = 0; i<argc; i++) printf("%d \t %s \n", i, argv[i]);
printf("\n");
return 0;
}
And output is similar to:
The following arguments were passed to main():
0 D:\Projects\test\vcpp\bcppcomp1\Debug\bcppcomp.exe
1 -P
2 TestHostAttoshiba
3 _http._tcp
4 local
5 80
6 MyNewArgument
7 200.124.211.235
8 type=NewHost
9 test=yes
10 result=output

Resources