简体   繁体   中英

Using a shell script in C++

I have to write a C++ program to pass a command line argument into a shell script. My code will compile but when I try to run the program with the argument it starts a new line like it's waiting for input instead of passing the argument into the script.

This is my C++ code:

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

char command[50];

int main(int argc, char *argv[])
{

        sprintf(command, "%s %s", "./findName", argv[1]);
        system(command);
}

I'm running the file from a unix terminal like this:

./findName someargument

working.cpp

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

char command[50];

int main(int argc, char *argv[])
{

        sprintf(command, "%s %s", "./findname", argv[1]);
        system(command);
}

and findname

#!/bin/bash
echo "hello $1"

In terminal

$gcc -o working working.cpp
$./working world
hello world

You obviously can't put the name of your cpp program in the command to system as it will call itself forever.

What does findName.sh does? Nothing you said is about waiting for input. And furthermore, if that is the name of the shell script, that is what you should put in the sprintf line, upper case N , .sh at the end and all....

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