I am trying to call system from a cpp program with the following command
system("ln -s -t \"targetDir[0]\" \"baseDir[0]\"");
Both targetDir and baseDir are QStringList. The program compiles and runs but when I execute the command i get the error ln : targetDir[0] is an invalid command. When I test by hard coding the values instead of using variables it works just fine. I can only conclude it is not escaping the string to put the value of the variables int the argument passed to ln. For the life of me I can't figure out why not.
Any Ideas?
You are confused. The system(3) library function (it is not a command, and despite its name is not a system call , those are listed in syscalls(2) ) is forking a /bin/sh -c
process which obviously don't have any idea about the variables of your C++ program (at runtime, variables don't exist; there are only locations).
BTW, using system(3) without care can be dangerous because of code injection issues. Imagine in your (wrong) approach that the targetDir[0]
contains something like foo; rm -rf $HOME
foo; rm -rf $HOME
....
To make a symbolic link, forking a process is overkill. Just call the symlink(2) system call (which the ln(1) command will call if invoked as ln -s
)
The Qt library offers the QFile class with its QFile::link member function, or the static QFile::link (both will call symlink(2) )
Future (or recent) versions of C++, starting from C++17 , will provide the std::filesystem::create_symlink
function (which on Linux will call symlink(2) ). It is probably inspired by Boost filesystem library.
PS. If coding for Linux or POSIX I recommend reading Advanced Linux Programming (which is freely downloadable). But if you want a source-portable Qt program restrict yourself to the generous Qt API. Or adopt C++17 and use its std::filesystem
thing.
C++ by no means performs string interpolation.
If you are actually writing in C++, you can (considering targetDir
is char **
or something alike):
std::string command = std::string("ln -s -t \"") + targetDir[0] + "\" \"" + baseDir[0] + "\"";
system(command.c_str());
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.