Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I have a program that does two separate things. But I want to the program to only run one specific part based on what I enter in the command like in the format
program -a
program -s
where the a or s would be programmed to tell it to do something specific.
For example, if my program was something like:
# program -a entered
z = x + y
# program -s entered
z = x - y
Now I could easily do this with an if statement after running the program, but is it possible to directly skip to a statement like I said from the command prompt?
int main(int argc, char* argv[]) {
if (argc >= 2) {
if (strcmp(argv[1], "-a") == 0) {
z = x + y;
} else if (strcmp(argv[1], "-s") == 0) {
z = x - y;
}
}
return 0;
}
Determine if the value of argv[1] equal to "-a" or "-s"
You can use a switch statement on command-line arguments (in this case argv[1]).
argv[1] is a string containing the options you have given ("-a", "-s" etc).
But you have to perform certain checks for the validity of the command-line arguments before you can use them like this.
Check if argc == 2
Check if strlen(argv[1]) == 2
Check if argv[1][0] == '-'
An MCVE would look like this:
#include <stdio.h>
#include <string.h>
int main(int argc, char* argv[]) {
if(argc == 2 && strlen(argv[1]) == 2 && argv[1][0] == '-')
{
switch(argv[1][1])
{
case 'a':
//do something
break;
case 's':
//do something else
break;
default:
//do the default thing
break;
}
}
else
{
//print appropriate error message
}
}
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 months ago.
Improve this question
I am trying to write an argument to a string. What am I doing wrong?
How would it be more correct to write the argument from getopt to a string?
#include <string.h>
#include <unistd.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
char fsrt[100], sstr[100], tstr[100];
int rez = 0;
while ( (rez = getopt(argc, argv, "f:s:l:")) != -1 )
{
if (rez == 'f') {
strcat(fsrt, optarg);
}
if (rez == 's') {
strcat(sstr, optarg);
}
if (rez == 'l') {
strcat(tstr, optarg);
}
}
printf("%s %s %s", fsrt, sstr, tstr);
return 0;
}
Update:
strange symbol in output.
./test -f one -s two -l three
output: https://i.stack.imgur.com/kksVh.png
char fsrt[100] = "", sstr[100]= "", tstr[100]= "";
If you don't initialize the char arrays they randomly point somewhere in memory.
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;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
TL;DR - My issue is that I can't seem to get both options to work. Only '-n' is working. I also want '-h' to work.
I am trying to create a program that essentially prints out the last few letters of '.txt' or '.log' file. However, I am running into an issue using getopt(). I am trying to access the different cases using the command line, but I can only access the first case
I have already tried include the colon (:) after "nLh" however it ends up outputting a "segmentation fault" (core dumped)" error.
Ex1: ./print.out -h (fails)
What I pass in
./print.out -h
Expected output
Usage: ./print.out -n
Actual output
Segmentation fault (core dump)
Ex2: ./print.out -n 60 (Successful)
What I pass in
./print.out -n 60
Expected output
Random text file from a txt file ... Random text file from a txt file
Actual output
Random text file from a txt file ... Random text file from a txt file
if(argc >1)
{
while ((option =getopt(argc,argv,"nLh"))!=-1)
{
switch (option)
{
case 'n':
if( isExtensionTXTorLog && charactersRead >0)
{
}
else if( argc == 3 && !isExtensionTXTorLog)
{
}
else
{
exit(2);
}
break;
case 'L':
break;
case 'h':
printUsage();
break;
case '?':
exit(0);
break;
default:
break;
}
}
}
else
{
accessDefault(buffer);
return 0;
}
You're using optind in the wrong way. optind is used to get non-options argument after parsing all the options. To parse option with argument use n:, then read optarg variable
Take look at this minimal example:
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char option;
int n_param;
while ((option =getopt(argc,argv,"n:h"))!=-1)
{
//Variable initialization
switch (option)
{
case 'n':
n_param = atoi(optarg);
printf("Param N: %d\n", n_param);
break;
case 'h':
printf("Help\n");
exit(0);
break;
case '?':
printf("Unrecognized option\n");
exit(0);
break;
default:
break;
}
}
for (int index = optind; index < argc; index++)
printf ("Non-option argument %s\n", argv[index]);
return 0;
}
Example:
./a.out ARG1 -n 50 ARG2
Output:
Param N: 50
Non-option argument ARG1
Non-option argument ARG2
This question already has answers here:
How do I properly compare strings in C?
(10 answers)
Closed 5 years ago.
I recently wrote a brute force program to turn the octal data from permissions in Unix into the human readable form (e.g. 755 -> rwxr-xr-x) However whenever I run my program called myperm I don't get a result (e.g. ./myperm 755 -> nothing) and I'm not quite sure why can anyone help with this
#include <stdio.h>
#include <string.h>
int main (int argc, char *argv[])
{
if (argv[1] == "777")
{
printf("rwxrwxrwx");
}
else if (argv[1] == "755")
{
printf("rwxr-xr-x");
}
else if (argv[1] == "750")
{
printf("rwxr-x---");
}
else if (argv[1] == "700")
{
printf("rwxr-x---");
}
else if (argv[1] == "666")
{
printf("rw-rw-rw");
}
else if (argv[1] == "664")
{
printf("rw-rw-r--");
}
else if (argv[1] == "640")
{
printf("rw-r-----");
}
else if (argv[1] == "600")
{
printf("rw-------");
}
else if (argv[1] == "400")
{
printf("r--------");
}
return (0);
}
Comparing strings in C doesn't work like this, you have to use strcmp
Instead of doing if (argv[1] == "XXX"), you should do if (strcmp(argv[1], "XXX") == 0)
Read on here
argv[1] == "755"
is not how you compare strings in C, you need to use:
strcmp (argv[1], "755") == 0
In any case, this "brute force" method is both totally unnecessary and unreliable (missing possibilities, only nine of the 512 possibilities are handled, even without taking into account setuid and setgid bits and so on).
You would be better off having a function to evaluate one octal digit, such as:
static const char * permXlat (char octal) {
switch (octal) {
case '0' : return "---";
case '1' : return "--x";
case '2' : return "-w-";
case '3' : return "-wx";
case '4' : return "r--";
case '5' : return "r-x";
case '6' : return "rw-";
}
return "rwx";
}
and then processing the argument one character at a time:
printf ("%s%s%s\n",
permXlat (argv[1][0]),
permXlat (argv[1][1]),
permXlat (argv[1][2]));
adding whatever sanity checking you think is necessary (argument list size, character values and so on).
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
When prompting the user to enter there name, it is necessary that the user indeed entered a name and not just whitespace.
Output ex:
Name:
Your name is: /user entered only whitespace/
How would one validate that characters were actually implemented, and not just spaces? Im using fgets() to retreive my input however i am unable to post the code now for I am at work and doing this off my mobile device. If code is nessesary i will post what im working on late tonight (pacific standard time). Thank you!
One way to test is to check all characters if they are space.
#include <stdio.h>
#include <stdlib.h>
// TODO: you should use bool instead
int is_all_space(const char *s)
{
char *tmp;
tmp = (char *) s;
// you might check for '\n' instead in your case
// or even '\r'
while (*tmp != '\0') {
// TODO: this check will fail if the input has zero length
if (*tmp != ' ') {
return 0;
}
tmp++;
}
return 1;
}
// don't forget to put the argument in quotes if it contains spaces
int main(int argc, char **argv)
{
if (argc < 2) {
fprintf(stderr, "Usage: %s somestring\n", argv[0]);
exit(EXIT_FAILURE);
}
if (is_all_space(argv[1])) {
puts("Input is all-space and nothing else");
} else {
puts("Input it not all-space");
}
exit(EXIT_SUCCESS);
}