Send a command to Terminal via C++

Asked

Viewed 2,027 times

3

How to send a code to the terminal?

For example: on a graphical screen where I type the name of a folder, and it sends to the terminal a mkdir NomePasta ? (Of course, there will be other features, like running programs for example, but I just need to know how to send the command).

2 answers

3


You can use the function system. However, I must warn you to be very careful with it. Firstly why this command will send the argument directly to the terminal, which will run according to the user’s environment. So maybe the command doesn’t do what you expect it to do. If a alias for mkdir, or if the executable itself has changed.

Another problem is that with the argument given by the user. If he says the folder name is documentos && rm -rf /, you will cause damage to the computer if you run the command like this. It is something very similar to SQL Injection (search).

The solution is to do what you want to do with the command, without using the command. For example, if you want to create a directory, how about using the function mkdir that is perfectly safe and does exactly what the documentation says it does? In short: look for alternatives.

  • Hi William, you’re right about the Injection, but as it will be for internal use there should be no problems... I don’t see alternatives, I gave the example of the folder but actually I need to call other scripts passing the name of the file as parameter (that is, I give a Browse with input in the name, and I play with the predefined commands to automate the procedure).

2

It’s already been one millennium time I don’t mess with C / C++ but I think it might help you.

#include <stdlib.h> 

    int main (int argc, char* argv[]) 
    { 
       system("mkdir NomePasta");
       return 0;
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.