I'm just trying to check the commandline arguments and see if it works in the command line. It works fine if I execute './a.out hello' but when I do './a.out' I get the error.
#include <stdio.h>
int main(int argc, char * argv[]){
printf("Test");
printf("\n%s",argv[0]);
printf("\n%s",argv[1]);
return 0;
}
The reason why I'm doing this is because I'm going to take that string and compare it later on. I don't understand why something this simple is causing an error.
You're not checking the length of argv before dereferencing the second argument. If argv only has one element argv[1] is a null reference, which causes your fault.
With C everything needs to be done carefully. To answer your question, yes, an if statement is the right approach if you want to handle the command line yourself. The argc parameter to main() is provided for exactly this purpose.
#include <stdio.h>
int main(int argc, char * argv[]){
printf("Test");
if (argc > 0) {
printf("\n%s", argv[0]);
if (argc > 1) {
printf("\n%s", argv[1]);
}
}
return 0;
}
Theoretically argv[0] is always populated with the application name so the first if is redundant but with C caution is your friend.
However, don't take this path. For everything except trivial applications you should use a parameter parsing library such as http://www.gnu.org/software/libc/manual/html_node/Getopt.html, check Christian's excellent answer here https://stackoverflow.com/a/24479532/2381157 for more options.
Related
I've got a text file that contains a bunch of strings, nothing important in terms of my problem.
The code here compiles/runs, and If I type in the correct text file, the first if statement runs. However, if I don't the else statement doesn't execute, but instead I get a seg fault, would Mallocing the pointer be of any help here? Any help would be much appreciated.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
int main (int argc, char * argv[])
{
FILE * ptr;
if(strcmp(argv[1],"test.txt") == 0)
{
printf("Right text file was inputted");
}
//but if I wan't the alternative (if the user didn't enter the right thing
else
{
// this never executes, but instead the program just seg faults if the first if statement is not true
printf("You didn't enter the right textfile, or none at all");
exit(1);
}
}
You should be using argc (the count of the number of arguments given) to determine if a value is entered or not. As it stands, accessing argv[1] when argc is 0, will cause a segmentation fault as you're accessing passed the end of the array when strcmp dereferences the terminating NULL pointer.
Your first if statement should be:
if(argc > 1 && strcmp(argv[1],"test.txt") == 0) {
...
when you pass arguments to main(), they are passes in the form of strings to main(). argc is a count of the arguments passed to the main() and argv is argument vector which is always NULL ended. so if you dont provide any arguments you have to first check with argc count and then proceed. other thing is you cannot check if wrong file name is passed or file name is not passed at all in just one condition
it should be like,
int main (int argc, char * argv[])
{
FILE * ptr;
if(argc>1)
{
if(strcmp(argv[1],"test.txt") == 0)
{
printf("Right text file was inputted");
}
else
{
printf("You didn't enter the right textfile");
exit(1);
}
}
else
printf("you havn't entered any file name");
}
I'm working on a C program with some system calls and I'm saving variables as follows:
int inhandle,outhandle,bytes,read_while_writing_nhandle;
char source[128],target[128];
Right now my program prompts the user with
printf("enter source file name\n");
scanf("%s",source);
How can I change it so a user can just type "run sourceName targetName"
aka, storing them as argv[1] and argv[2]?
I also use the inputs (target and source)
in handles like:
inhandle=open(source,O_RDONLY);
My main issue is conversion since I'm storing target and source as char. I could use something like strcpy.
It would just be very much appreciated if someone could help me out with it. Hope this was clear. Thank you.
*********EDIT: I apologize, I probably wasn't clear enough...
I tried doing the int main(int argc, char *argv[]) and then including:
if(argc==3)
{ source = argv[1]; target = argv[2]; }
else{ printf("Syntax error.\n");
return -1;
But I'd get conversion errors since I can't store them that way. And if I do store them as pointers (like *target=argv[2]) I'm worried they won't work when I call the handles.. (ex: outhandle=open(target...) works but I can't do open(*target..)
Use int main(int argc, char **argv);
And then assign source to argv[1] and target to argv[2]
Change to:
if(argc==3)
{
strcpy(source, argv[1]);
strcpy(target, argv[2]);
}
Also, read up on the dangers of strcpy, and consider strncpy.
But using strcpy will get you started at least...
So I have a program which takes a command line argument from the user and uses atoi to convert it to a number. It all works fine until the number that is passed from the command line is more than 2048.
Here is the simple program:
int no_of_elements_per_thread = 0;
int main(int argc, char* argv[])
{
int status;
void* thread_arg;
void* res;
int i = 0;
//initialize
no_of_elements_per_thread = atoi(argv[1]);
return 0;
}
When I run the program for different values the output is as follows:
[adeb1][open-19][~/pre2] ./pre2 2098
Segmentation fault
with smaller values:
[adeb1][open-19][~/pre2] ./pre2 210
[adeb1][open-19][~/pre2]
Interestingly if I try to do a printf with %s without doing atoi I still get segmentation fault as well with argv[1]. So it seems argv[1] is giving problem with values higher than 2048.
I am using gcc in linux if that matters.
Where is your declaration of atoi? Without #include <stdlib.h>, I would assume there is none.
You may also want to ensure argc > 1 before using argv[1].
I've built a C application, and when I build it, it shows no errors, but when I run it, it gives me the error "Segmentation Fault: 11".
If it helps, here is the code I am using:
#include <stdio.h>
int main(char *argv[]) {
printf("The project path is: ./Projects/%c", argv[1]);
return 0;
}
The correct main prototyped syntax is
int main(int argc, char *argv[]) { ... }
Also %c conversion specification in printf prints a character, to print a string use %s.
You have a number of problems:
The signature for main is an argument count followed by an array of C strings.
You should always check the count before using the array.
The array is of strings so you need %s to print them.
This should work:
#include <stdio.h>
int main(int argc, char *argv[]) {
if (argc < 2)
fprintf (stderr, "Wrong number of arguments\n");
else
printf ("The project path is: ./Projects/%s\n", argv[1]);
return 0;
}
Change the signature to int main(int, char*[]);
What arguments are you passing to the process? If you're not passing any argv[1] is out of range
In addition to the other suggestions, you may need to revisit your printf format. %c is used to print a single character, and argv[1] is char *. Either use argv[1][0] or some such, or use the string format specifier, %s.
First, change your main to:
int main(int argc, char *argv[])
Second, you have a mismatch between what you're passing to printf, and what you've told it you're going to pass. argv[1] is a pointer to characters, not a character. You need/want to use the %s conversion to print it out:
printf("The project path is: ./Projects/%s", argv[1]);
In this specific case, it's not really mandatory to check for enough arguments, because even if you don't pass any command line arguments, argv will contain at least argv[0] followed by a null pointer. As such, using argv[1] is safe, but if you haven't passed a command line argument, may print as something like (null).
Nonetheless, you generally want to check the value of argc before using argv. In this case, you can get away with it, but only more or less by accident. Trying to use argv[2] the same way could give undefined behavior.
The problem that i have is that i have to write a hanois tower game in c and the input for the number of the rings must not be in the programm but the code must read the number of rings in the execution.
Example: ./hanoistower 3
And the code should get the 3 as the input. How can i do that?
Command line arguments are propagated as strings through the main() function of your C program.
In int main(int argc, char *argv[]) argc is the number of arguments, and argv is an array of strings containing the arguments. Note that the program name itself is always the first "argument".
As the arguments are passed as strings, you likely need to convert your 3 to an integer, which can be done with the atoi function. Here's a start:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int rings;
if(argc != 2) {
printf("Usage: %s number-of-rings\n",argv[0]);
return 1;
}
rings = atoi(argv[1]);
printf("Using number-of-rings = %d\n", rings);
...
return 0;
}
I strongly suggest reading a good C programming book (in 2020, Modern C).
It will be much faster than asking questions here. Don't forget to also read the documentation of your C compiler (perhaps GCC), your build automation tool (e.g. GNU make or ninja), and debugger (perhaps GDB). If you code on and for Linux, read also Advanced Linux Programming and syscalls(2), and the documentation of GNU glibc (or of musl-libc, if you use it).
Hovever, the program arguments is given as a null terminated array of strings to the main function, which is usually declared as
int main (int argc, char**argv) { /*...*/ }
if you run your program with ./hanoistower 3 and if your hanoistower.c is your source code (which you need to compile with debugging and warning enabled, i.e. gcc -Wall -g hanoistower.c -o hanoistower on Linux) then you have one extra argument, so
argc == 2
argv[0] is the "./hanoistower" string
argv[1] is the "2" string (use atoi to convert it to an int)
argv[2] is NULL
Please, please learn to use the debugger (gdb on Linux).
Just add, argc and argv to the list of main method parameters, as shown below:
int main ( int argc, char *argv[] )
Then use argv as the variable to specify number of rings inside your code.