What Does Input Arguments is _ - c

I wanna know why is result 1 for no arguments.
int main(int argcount, char *arglist[]) {
int i;
printf("Number of arguments %d\n",argcount);
printf("Arguments list:\n");
for (int i=0;i<argcount;i++)
printf("%s\n",arglist[i]);
return EXIT_SUCCESS;
}

From the standard (C11), noting especially the bold bit:
If they are declared, the parameters to the main function shall obey the following
constraints:
The value of argc shall be nonnegative.
argv[argc] shall be a null pointer.
If the value of argc is greater than zero, the array members argv[0] through
argv[argc-1] inclusive shall contain pointers to strings, which are given
implementation-defined values by the host environment prior to program startup. The
intent is to supply to the program information determined prior to program startup
from elsewhere in the hosted environment. If the host environment is not capable of
supplying strings with letters in both uppercase and lowercase, the implementation
shall ensure that the strings are received in lowercase.
If the value of argc is greater than zero, the string pointed to by argv[0]
represents the program name; argv[0][0] shall be the null character if the
program name is not available from the host environment. If the value of argc is
greater than one, the strings pointed to by argv[1] through argv[argc-1]
represent the program parameters.
The parameters argc and argv and the strings pointed to by the argv array shall
be modifiable by the program, and retain their last-stored values between program
startup and program termination.
In other words, argc includes the argument representing the program name - the actual parameters to the program start at argv[1]. That becomes evident from the program output as per the following transcript, where the first argument is the program name:
pax> cat testprog.c
#include <stdio.h>
int main(int argc, char *argv[]) {
printf("Argument count: %d\n", argc);
printf("Arguments:\n");
for (int i = 0; i < argc; i++)
printf(" %s\n", argv[i]);
return 0;
}
pax> gcc --std=c11 -o testprog testprog.c && ./testprog 1 2 3
Argument count: 4
Arguments:
./testprog
1
2
3
pax> ./testprog
Argument count: 1
Arguments:
./testprog

./a.out is the first argument so that's why argcount equals to 1.

From the C Standard (5.1.2.2.1 Program startup. p.#2)
— If the value of argc is greater than zero, the string pointed to by
argv[0] represents the program name; argv[0][0] shall be the null
character if the program name is not available from the host
environment.
So the used by you environment supplies the program name in the first argument.

Related

Segmentation fault when file is not found even if I try to create it in C

I'm writing a code that appends text to a file.
It uses fopen in the beginning of WriteToFile so even if the file does not exist, it creates it.
But, what happens when I enter no file at all? no arguments at all? Just ./a.out?
Segmentation fault.
I don't know why, it seems to me I did everything fine to avoid any problems.
int main(int argc, char **argv)
{
char file_name[30] = "file.txt";
printf("%s",file_name); /* for debugging : doesn't print it */
if (0 != argc)
{
strcpy(file_name, argv[1]);
}
WriteToFile(file_name);
}
OR
(in case I can't really put a string literal into char array):
char file_name[30];
if (0 == argc)
{
strcpy(file_name, "file.txt");
}
else
{
strcpy(file_name, argv[1]);
}
For both of the cases i'm getting
Segmentation fault (core dumped)
if (0 != argc)
The argc value is normally(a) the count of arguments including the program name. Hence, running ./a.out will have an argc of one rather than zero. And, since argv[argc] is usually NULL, dereferencing it is not going to end well :-)
If you want to ensure another argument is available, you can use:
if (argc > 1) { // Have both argv[0] AND argv[1].
nowSafeToUse(argv[1]);
}
In more detail, the C11 standard states:
If they are declared, the parameters to the main function shall obey the following constraints:
The value of argc shall be nonnegative.
argv[argc] shall be a null pointer.
If the value of argc is greater than zero, the array members argv[0] through argv[argc-1] inclusive shall contain pointers to strings, which are given implementation-defined values by the host environment prior to program startup. The intent is to supply to the program information determined prior to program startup from elsewhere in the hosted environment. If the host environment is not capable of supplying strings with letters in both uppercase and lowercase, the implementation shall ensure that the strings are received in lowercase.
If the value of argc is greater than zero, the string pointed to by argv[0] represents the program name; argv[0][0] shall be the null character if the program name is not available from the host environment. If the value of argc is greater than one, the strings pointed to by argv[1] through argv[argc-1] represent the program parameters.
The parameters argc and argv and the strings pointed to by the argv array shall be modifiable by the program, and retain their last-stored values between program startup and program termination.
As an aside regarding this line:
printf("%s",file_name); /* for debugging : doesn't print it */
If this is not printing, it's probably because standard output is line buffered (default if it's determined to be an interactive device, otherwise fully buffered).
By not outputting a \n at the end, the characters are probably still sitting in a buffer somewhere, ready to be written. The crash will probably kill off the process without flushing the buffer. So a simple solution may be just to use one of:
printf("%s",file_name);
puts(file_name);
As another aside, you're going to get into trouble if the filename you enter is larger than 29 characters since it will overflow file_name, allowing for the \0 at the end as well.
A better approach may be just to use either your default string or argv[1] directly (without copying), something like:
int main(int argc, char **argv) {
char *file_name = (argv > 1)
? argv[1]
: "file.txt";
printf("%s\n", file_name); // for debugging : probably does print it :-)
WriteToFile(file_name);
}
(a) Not required by the standard since it allows for implementation-specific differences, but it's the usual case. Specifically, the phrase:
... which are given implementation-defined values by the host environment prior to program startup. The intent is to supply to the program information determined prior to program startup from elsewhere in the hosted environment.
pretty much means it can do whatever it wants :-)
A related answer (though a non-duplicate question) can be found here.
When argc is 1, argv is treated as an array of 2 pointers to char. The first is a valid pointer (typically to the program name), the second is NULL.
argv[1] accesses the second element of argv. With no arguments supplied, argc will be 1 and argv[1] will be NULL. You're therefore dereferencing a NULL pointer.
The condition 0 != argc should instead be argc >= 2 or argc > 1, and the condition 0 == argc should be argc < 2 or argc <= 1.
You have to account for the program's name so you should write if (argc >= 2) instead. See the man
The value of the argc argument is the number of command line arguments. The argv argument is a vector of C strings; its elements are the individual command line argument strings. The file name of the program being run is also included in the vector as the first element; the value of argc counts this element. A null pointer always follows the last element: argv[argc] is this null pointer.
argv[1] means index 1 but in C you start at index 0.
Fixed code
int main(int argc, char **argv)
{
char file_name[30] = "file.txt";
printf("%s",file_name); /* for debugging : doesn't print it */
if (argc >= 2)
strcpy(file_name, argv[1]);
else
return 1; // exit program with error code.
WriteToFile(file_name);
return 0; // exit with success
}

What is the definition of an "argument in C"

I'm having some trouble reading a line of the code, and understanding what constitutes an argument in the context of this line of code. This is saved in a file called argv0.c
#include <cs50.h>
#include <stdio.h>
int main(int argc, string argv[])
{
if (argc == 2)
{
printf("hello, %s\n", argv[1]);
}
else
{
printf("hello, world\n");
}
}
I compile the code as follows:
make argv0
./argv0
following which I am prompted for an input. Herein lies the issue:
if I type in "Dion Lim" in the terminal, is Dion Lim considered an argument? If so, is it two arguments?
Why is it that if I type in "Dion Lim" in the terminal, I get "Hello, World", but if I type in "Dion" i get "Hello,Dion"
Q1) Yes, they are two arguments.
Q2) Because argc consider the name of executable it's the first parameter. So:
./argv0 Dion Lim // argc == 3
./argv0 Diom // argc == 2
./argv0 // argc == 1
You can get more detail here.
if I type in "Dion Lim" in the terminal, is Dion Lim considered an
argument? If so, is it two arguments?
It depends on how your shell handles it of course, but usually "Dion Lim" would be one argument while Dion Lim (without the quotation marks) would be two arguments. The space delimits the arguments, and with the quotes you can work around that if you want space in your input (sometimes you can also escape the space, like Dion\ Lim).
Why is it that if I type in "Dion Lim" in the terminal, I get "Hello,
World", but if I type in "Dion" i get "Hello,Dion"
The argc parameter tells you how many arguments you have (I think of it as standing for "argument count"). The program's name also counts as an argument, so if you only pass Dion, then argc will be 2 already. If you pass Dion Lim, it will be 3.
To see the number of arguments check the value argc (arguments count). There is always at least one input argument, which is the program name.
So with./argv0 Dion Lim there are three input arguments.
If you are wondering make compiles the program using Makefile so if look in the directory you from which you are running make you will find a file named Makefile containing the compilation instructions.
According to the C Standard (5.1.2.2.1 Program startup)
— If the value of argc is greater than zero, the string pointed to
by argv[0] represents the program name; argv[0][0] shall be the null
character if the program name is not available from the host
environment. If the value of argc is greater than one, the strings
pointed to by argv[1] through argv[argc-1] represent the program
parameters.
So if you "manually" supply the argument Dion then argc will be exactly equal to 2. The first program parameter will be the program name (as it is followed from the quote) and the second program parameter will be the word Dion.
If you will type Dion Lim then the host system considers them as two program parameters and together with the program name argc will be equal to 3.
However if you enclose the input Dion Lim in parentheses like "Dion Lim" then the system will consider the input as one parameter and your program will output
hello Dion Lim

Why aren't there any passed arguments to argv[]?

So, I noticed that my argc is always 1 as I will always get the message Error: missing command line arguments!, but as stated in code I am using argv[1] and argv[2] to read the files names.
Shouldn't automatically argc be 3 in this case, and to be able to pass that error?
Notes:
If I am not using if (argc < 2) statement, after I enter the name for the output file my program crushes.
For the input file I already have this one created in the project folder, so I just enter the name of that file.
This is the code:
#include <stdio.h>
#include <stdlib.h>
FILE *IN, *OUT;
int main(int argc, char* argv[])
{
if (argc < 2)
{
printf("Error: missing command line arguments!\n");
return 1;
}
printf("Enter the name of the file with the input data: ");
scanf("%s", argv[1]);
printf("\nEnter the name of the file for the output data: ");
scanf("%s", argv[2]);
IN = fopen(argv[1], "r");
OUT = fopen(argv[2], "w");
fclose(IN);
fclose(OUT);
return 0;
}
You're complete mis-understanding the purpose of argc and argv. They are supposed to receive the supplied command line argument (program parameters) before the program startup, not supposed to hold the scannned input at runtime.
Quoting C11, chapter §5.1.2.2.1,
If they are declared, the parameters to the main function shall obey the following
constraints:
— The value of argc shall be nonnegative.
— argv[argc] shall be a null pointer.
— If the value of argc is greater than zero, the array members argv[0] through
argv[argc-1] inclusive shall contain pointers to strings, which are given
implementation-defined values by the host environment prior to program startup. The
intent is to supply to the program information determined prior to program startup
from elsewhere in the hosted environment.
and
If the value of argc is greater than zero, the string pointed to by argv[0]
represents the program name; argv[0][0] shall be the null character if the
program name is not available from the host environment. If the value of argc is
greater than one, the strings pointed to by argv[1] through argv[argc-1]
represent the program parameters.
To elaborate, when a program is invoked like
./a.out three total arguments
then, in your program
argc will be 4
argv[0] will be ./a.out
argv[1] will be three
argv[2] will be total
argv[3] will be arguments
argv[4] will be NULL (see the property for argv[argc] above)
(To generalize, argv[1] - argv[argc-1] will hold the supplied arguments, argv[argc] will be NULL)
You don't need to explicitly scan the input, those values will be populated from the host environment.
On the other hand, you cannot just invoke the program like
./a.out
and exptect argc to be 3 (or any other value, other than 1, for that matter) and argv[1] - argv[n-1] to be valid because at compile-time the invokes program has no way to know that you plan to supply some values at runtime. It's not clairvoyant.

Printing integers from command line arguments in C

I'm running my program with some command line arguments. But when I enter 10, 10, 10 and print them out, it prints out 49, 49, 49. Here's my code:
int main(int argc, char *argv[]) {
int seed = *argv[0];
int arraySize = *argv[1];
int maxSize = *argv[2];
Why is this happening??
Well, argv is an array of pointer to strings. All command line arguments are passed as strings and the pointer to each of them is held by argv[n], where the sequence for the argument is n+1.
For a hosted environment, quoting C11, chapter §5.1.2.2.1
If the value of argc is greater than zero, the string pointed to by argv[0]
represents the program name; argv[0][0] shall be the null character if the
program name is not available from the host environment. If the value of argc is
greater than one, the strings pointed to by argv[1] through argv[argc-1]
represent the program parameters.
So, clearly, for an execution like
./123 10 10 10 //123 is the binary name
argv[0] is not the first "command line argument passed to the program". It's argv[1].
*argv[1] does not return the int value you passed as the command-line argument.
Basically, *argv[1] gives you the value of the first element of that string (i.e, a char value of '1'), most possibly in ASCII encoded value (which you platform uses), ansd according to the ascii table a '1' has the decimal va;lue of 49, which you see.
Solution: You need to
Check for the number of arguments (argc)
Loop over each argument string argv[1] ~ argv[n-1] while argc == n
Convert each of the input string to int (for this case, you can make use of strtol())
Dereferencing a string (*argv[x]) gives you a char (the value of the first character in the string), in this case the value is ASCII '1': decimal 49
You can convert those strings (without dereferencing) using strtol
int arraySize = (int)strtol(argv[1], NULL, 10);
Anyway argv[0] is the name of your program, are you sure that the program name starts with 1?

segmentation fault checking user arguments c

I am trying to validate user input from the command line with argc and argv but am running into a segmentation fault and am not sure why.
I want to validate the user has entered a positive int (so argc =2 and argv is positive).
Here is my code:
int main (int argc, string argv[])
{
int k = atoi(argv[1]);
if (argc != 2 && k <1)
{
return 1;
}
}
The k < 1 part of my code seems to be working fine, but I get segmentation errors every time I try to run without the program name and an argument (agrc !=2).
EDIT:
More clear description of the error handling problem:
If I run ./myprogram -2
then I get my return 1 as expected.
If I run ./myprogram hjdksfhdsk
then I get my return 1 as expected.
If I run ./myprogram
then I get a segmentation fault.
It is this behaviour that makes me think my handling of the argc value is at fault, but I am not sure why I cannot just test argc !=2.
This is incorrect, since in C string is not a built-in type (and is not a standard type defined in some standard header - notice that C++ has std::string defined in its <string> standard header).
The signature of main has to be
int main(int argc, char**argv);
The convention is that argv[argc] is the null pointer, and the argc pointers from argv[0] to argv[argc-1] are non-null pointers to null-terminated strings.
Notice that (at least on Linux and Posix systems) program arguments are not user input to the program. The shell has been given a command line as input and has expanded that command line into program arguments. Your program could later read some input, e.g. with scanf.
You cannot convert a NULL pointer with atoi, so you should check argc before doing the conversion.
int main(int argc, char**argv) {
if (argc!=2) {
fprintf(stderr, "%s needs two arguments\n", argv[0]);
exit(EXIT_FAILURE);
};
int k = atoi(argv[1]);
if (k<=0) {
fprintf(stderr,
"%s wants a positive first argument, but got %s\n",
argv[1]);
exit(EXIT_FAILURE);
}
// now do the real thing
}
BTW, I believe that (at least on Linux or Posix system) a program should accept the --help argument per the GNU coding standard. I suggest you to use getopt (notably getopt_long) or argp to parse program arguments.
At last, compile with all warnings and debug information (e.g. with gcc -Wall -g) and learn how to use the debugger (e.g. gdb).
Your main should be
int main(int argc, char*argv[])
And do the check before using on atoi on argv[1]
Also all paths should return a value. Bung return 0; at the end
As others have noted string is not a base type. However since you are getting results in one case your segmentation fault has to do with the atoi on argv 1. In c arrays are 0 based so you're trying to convert uninitialized memory. Use the argc test before the atoi.

Resources