简体   繁体   中英

How do I create a C++ program that passes command line arguments to a shell script?

I have never used C++ before and my professor said this is supposed to be "very simple", but I can't figure it out. This is what I have so far:

#include <iostream>
#include <cstdio>
#include <cstdlib>

int main(int argc, char *argv[])
{
  char command[50];
  if (argc==2)
    system(command, "./findName.sh", argv[1]);
}  
return 0;

My shell script works when I run it by itself but I am not sure how to use a C++ program to run it. For the shell script, the user is supposed to enter a user ID like this:

./findName.sh userID

and the program returns the person's name from a file of names and user IDs like this:

LastName, FirstName

For the C++ program, it needs to pass the information the user enters to the shell script and return the same results.

As I said, I have never used C++ before so I don't know if any of this is right. It is a mix of things I have found online. Thank you for all of your help!!

The easiest way I find to do this is to use std::string as it allows you to concatenate stings easily.

#include <string>
#include <cstdlib>

int main(int argc, char* argv[])
{
    std::string command = "./findName.sh";

    if(argc == 2)
        std::system((command + " " + argv[1]).c_str());
}

But to understand why this works you are going to need to study some books .

First you need to compile the program before you can run it. If your source code file name is progname.cpp you should be able to use this command:

g++ -o progname progname.cpp

And then run the program like this:

./progname userID

1) system("abc.sh " + para1 + " " + para2); But this method have a limitation, the max length you can pass into is MAX_ARG_STRLEN is defined as 131072 bytes=32 pages of memory.

2) open a file and read all the value to the file system("abc.sh < yourfile.txt"); This method is a bit indirect, but you can put unlimited size of value to sh inside the sh, use a normal read from buf ( or keyboard )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM