I'm relatively new to c++, and I'm just making some simple programs.
One of my programs will need to open up a different .exe file. This .exe file will ask for 2 or 3 file names, then run and exit.
Just to test this out, I created a simple_calc.exe file, that ask for value1, then value2 then multiply them.
So let's say I want to create a "call_other_file.exe" and automatically run "simple_calc.exe" with value1 and value2 taken from "call_other_file.exe"s file.
How can I proceed to do that?
After searching a bit, i see something like:
system("simple_calc.exe -val1 -val2").
But that doesn't work for me. Or I'm not sure how to define val1 and val2...
edit: the program I want to access (simple_calc.exe in the example), I can not change the code there, I don't have access to it's .cpp file.
Any suggestions?
i see something like: system("simple_calc.exe -val1 -val2")
It should work. The reason why that didn't work might be that you didn't put int argc, char* argv[] in your "simple_calc"'s main function.
//simple_calc.cpp
int main(int argc, char* argv[])
{
if (argc == 2)
{
cout << "Error: At least two argument must be exist.";
return -1;
}
return 0;
// After that, you can use 'argv' arguments to calculate what you want to calculate. Also, in order to calculate them, you also need to convert 'argv' to integer or double, since they are string or char array.
}
For more information on C++ comand-line arguments see this site below:
http://www.tutorialspoint.com/cprogramming/c_command_line_arguments.htm
When you add the command-line arguments to your simple_calc.cpp, you can use this simple_calc.exe val1 val2. To call another program from your C++ program, you need system calls. In your main function;
system('simple_calc.exe')
You also need to know about how windows console work, if you are using windows. If you are using linux, its console commands are also different.
My suggestion is that you must first learn how consoles work different operating systems.
There are various ways to have two separate programs communicate with one another, but the system() function is probably the simplest; it just runs a string of text as though it were entered in a console window.
Basic example
The main program simply runs the other program with two arguments: hello and world.
/* main.c */
#include <stdlib.h>
int main() { return system("./other hello world"); }
The two arguments will be passed to the other program as C-style strings via the argv[] array. Note that they will be stored as the second and third elements, since the first item (argv[0]) will be the path to the program itself.
/* other.c */
#include <stdio.h>
int main(int argc, char *argv[])
{
int i = 0;
for (i = 1; i < argc; ++i) { printf("%s\n", argv[i]); }
return 0;
}
The output of the above programs will look like this:
hello
world
Process returned 0 (0x0) execution time : 0.004 s
Press ENTER to continue.
Arguments with spaces
As you may have noticed, arguments are space-separated. If you need to pass a string with spaces as a single parameter, you'll need to enclose it in quotes:
/* main.c */
#include <stdlib.h>
int main() { return system("./other \"this is all one string\" \"and so is this\" bye"); }
This would produce the following result:
this is all one string
and so is this
bye
Process returned 0 (0x0) execution time : 0.004 s
Press ENTER to continue.
Non-string arguments
Since the arguments are given as strings, you'll need to convert them into numbers (using conversion functions such as strtod(), atoi(), or atof()) if necessary. Here's an updated version of main.c:
/* main.c */
#include <stdlib.h>
int main() { return system("./other 4 6"); }
...and here's the corresponding other.c file:
/* other.c */
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int total, i;
for (total = 0, i = 1; i < argc; ++i) { total += atoi(argv[i]); }
printf("TOTAL: %d\n", total);
return 0;
}
This produces the following output:
TOTAL: 10
Process returned 0 (0x0) execution time : 0.005 s
Press ENTER to continue.
Related
Long story short:
I created a program to get the path to a model file, do something with that information and pass on a different set of information, then i tried to create a wrapper for another program that basically catches the command line arguments and funnels some of them to my program to do its thing.
Simplified program flow.
Software --> args[all] --> Wrapper --> args[some] --> Program --> Output
The problem i now have is, calling my program on its own with hard-coded information or command line arguments equal to what the Wrapper would pass on works both flawlessly. The same goes for the Wrapper it works independently.
It also works to have the Wrapper pass on arguments and call the Program if the model information is wrong, which results in a simple string warning. But if the path to the model is correct it gets stuck in an endless loop and i don't know why. Separate runtimes are 8-11s for the Program and maybe 2s for the Wrapper, but i let it run for about 10min and nothing happened after some dummy print code.
Wrapper:
int main(int argc, char* argv[]){
if(argc > 1){
string tmp0 = argv[1];
string tmp1 = "./program " + tmp0;
const char* model = tmp1.c_str();
int status = system(model);
}
else{
cout << "No Model Information.\n";
}
return 0;
}
Parameters would be: Path to a model file and some other stuff, but only the path to the model would be passed on to the program in this case.
Program:
#include "program.hpp"
int main(int argc, char* argv[]){
if(argc > 1){
string tmp = argv[1];
const char* model = tmp.c_str();
cout << program(model);
}
else{
cout << "At least one defined Argument for the Model needs to be given.\n";
}
return 0;
}
Program Function Pseudo Code:
#include <stdio.h>
string program(const char* model){
string tmp
read(model);
if(model has variables) do
tmp = "has variables";
return tmp
}
--- Edit ---
The program function code is in pseudo code because its too complex and specific to list here without a load of libraries and other stuff being listed. If thats necessary i can try to provide it, but as it is i dont have a small or simple example i can give.
--- End edit ---
I don't understand enough about command line arguments to write sophisticated code, so i know this is more or less shitty, but i only need to be able to execute the program from the wrapper somehow and need to be able to read and pass on specific command line arguments. This is just the best i came up with.
Executing the Program code alone, with correct model information: ~10s execution time
Executing the Program code alone, with wrong model information: ~2s execution time
Executing the Wrapper code alone: ~2s execution time
Executing the Wrapper code, calling the Program code with wrong model information: ~2s execution time
Executing the Wrapper code, calling the Program code with correct model information: endless wait
I just dont get why it doesnt progress even though each works separately.
You can use fork() and execvp() in the unistd.h API. Depending on the return of fork() you can have the wrapper wait or end after launching the command.
Save the source file as args.cpp and compile it with the following command:
$ g++ args.cpp -o args && ./args -l -h -a
#include <cstdio>
#include <unistd.h>
#define SPAWNCMD "ls"
int main(int argc, char* argv[])
{
if(argc > 1)
{
printf("Command to spawn: %s ", SPAWNCMD);
for (unsigned i = 1; i < argc; i++)
printf("%s ", argv[i]);
printf("\n");
if (fork())
if (execvp(SPAWNCMD, argv) == -1)
{
printf("Incorrect termination of SPAWNCMD\n");
return 1;
}
}
else
{
printf("No Model Information.\n");
}
printf("Wrapper program end\n");
return 0;
}
I am trying to pass a command into my shell script via a C++ program, but I am not familiar with C++ at all and, while I know that I must use system(), I am not sure how to set it up effectively.
#include <iostream>
#include <stdlib.h>
int main() {
system("./script $1");
return 0;
}
This is what I currently have.
It seems that I can't use positional parameters in the system command, but I wasn't sure what else to do. I'm trying to pass in an argument to the script via the C++ program.
If you just want to call "./script" with the first argument to the C++ program passed as the first argument to the script, you could do it like this:
#include <iostream>
#include <string>
#include <stdlib.h>
int main(int argc, char ** argv)
{
if (argc < 2)
{
printf("Usage: ./MyProgram the_argument\n");
exit(10);
}
std::string commandLine = "./script ";
commandLine += argv[1];
std::cout << "Executing command: " << commandLine << std::endl;
system(commandLine.c_str());
return 0;
}
Properly executing a shell command from C++ actually takes quite a bit of setup, and understanding exactly how it works requires a lot of explanation about operating systems and how they handle processes. If you want to understand it better, I recommend reading the man pages on the fork() and exec() commands.
For the purposes of just executing a shell process from a C++ program, you will want to do something like so:
#include <unistd.h>
#include <iostream>
int main() {
int pid = fork();
if (pid == 0) {
/*
* A return value of 0 means this is the child process that we will use
* to execute the shell command.
*/
execl("/path/to/bash/binary", "bash", "args", "to", "pass", "in");
}
/*
* If execution reaches this point, you're in the parent process
* and can go about doing whatever else you wanted to do in your program.
*/
std::cout << "QED" << std::endl;
}
To (very) quickly explain what's going on here, the fork() command essentially duplicates the entire C++ program being executed (called a process), but with a different value of pid which is returned from fork(). If pid == 0, then we are currently in the child process; otherwise, we're in the parent process. Since we're in the dispensable child process, we call the execl() command which completely replaces the child process with the shell command you want to execute. The first argument after the path needs to be the filename of the binary, and after that you can pass in as many arguments as you want as null-terminated C strings.
I hope this helps, and please let me know if you need further clarification.
the problem I have understood so far is that you want to pass arguments to c++ executable and it will then pass those arguments further to the system script
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
// argc is the count of the arguments
// args is the array of string (basically the arguments)
int main(int argc, char ** argv) {
// Convetion to check if arguments were provided
// First one or two are the not positional. (these are information related to the binary that is currently being executed)
if (argc < 2) {
printf("Please Provide an Argument");
return 100; // Any number other than 0 (to represent abnormal behaviour)
}
string scriptCommand = "./name-of-script"; // script in your case
// Loop through and add all the arguments.
for (int i = 1; i < argc; i++)
scriptCommand += " " + argv[i];
system(scriptCommand.c_str());
return 0; // Represents a normal exit (execution).
}
I am up a wall on an assignment that I have been hacking at for several days. Basically I need to make an executable program using C/C++ to take 3 queries from the user m,n and a file name.
The program will then output the text on those lines to the terminal. I must use read(), write(), open() and close() system calls to do it.
My approach is to go char by char (slow I know but everything else I tried seems to give segementation faults).
But it doesn't seem to work properly. When I use smaller parameters it just prints the whole thing, but if I use bigger parameters it doesn't print anything at all.
Can anyone tell me where I'm going wrong?
// Task 2 of Lab 3
#include<unistd.h> // required library for the system calls
#include<fcntl.h> // required for system calls usage
#include <stdlib.h> // required for the use of exit statement, and atoi
#include<stdio.h> // required for the use of perror
#include<string>
using namespace std;
int main(int argc,char *argv[]){
int m = atoi(argv[1]);
int n = atoi(argv[2]); // taking commmand line args by conversion with atoi
int file; // integer value for holding the file descriptor
ssize_t display;
char *buff[1];
int currentLine = 0;
// open the first file for reading
file = open(argv[3],O_RDONLY);
if(file == -1 ){ // error handler for system call 1: open()
perror("Did not open, exiting...");
exit (1);
}
while(((display = read(file,buff,1)) > 0)){
if(*buff[0] == '\n'){
currentLine++;
}
if((currentLine >= m) && (currentLine <= n)){
if(write(STDOUT_FILENO, buff,display) != display){ // if statement doubles as error handling for read()
perror("Problem with writing..."); // errror handling for write()
exit(-1);
}
}
else{
}
}
file = close(file); // Final system call close()
return 0;
}
Sample testfile:
I have some information in here.
Each line should print to the screen
3 lines total
make that 4
Wait? WHAT! I need 12 minimum???
Hm....
Wellp better start typing then. Let's see what can I write about?
Midterms are coming
They scare me
I hate exams, but I love code
woah i also need numbers in here uh 23
19 and lets do 100 and 400 just to add a couple more
maybe i should go ahead and add a 903 here
300
and that previous 300 got it's own line
with this file ...
I have a good mix of chars,numbers, and symbols
that's good enough
time to test!
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 )
Here is were i get the error.
To explain, i want to print the → character which according to http://www.endmemo.com/unicode/unicodeconverter.php
The code is 2192. but i may be using the wrong code if so what is the right way to print → .
int _tmain(int argc, _TCHAR* argv[])
{
UINT oldcp = GetConsoleOutputCP();
SetConsoleOutputCP(CP_UTF8);
cout<<"\x2192"<<endl;
SetConsoleOutputCP(oldcp);
return 0;
}
A char on your platform is 8 bits. Your code part "\x2192" tries to put 16 bits in it. What will not fit, so you get the warning.
You possibly meant several characters, like "\x21\x92" or "\x92\x21"? That creates a valid string with two chars (+ the 0). You may still adjust it to have the proper value if comments are correct.
From the use of _tmain and SetConsoleOutputCP I guess you are mostly about Windows. I'm afraid I don't know much about that; hopefully someone who knows more about that specific case will chime in, but this program generates the output you're looking for in a quick test I tried here with a UTF-8 terminal. Here's the program:
#include <iostream>
int main(void)
{
std::cout << "\xE2\x86\x92" << std::endl;
return 0;
}
And example output:
$ make example && ./example
c++ example.cpp -o example
→
I just directly output the UTF-8 encoding of the → character.
Equivalently (at least for clang):
#include <iostream>
int main(void)
{
std::cout << "→" << std::endl;
return 0;
}