Frans-Willem Frans-Willem - 1 year ago 99
Bash Question

How to safely escape a string from C++

I'm writing a simple program to browse the local network and pass on filenames to mplayer using "system". However, sometimes filenames contain spaces or quotes.
Obviously I could write my own function to escape those, but I'm not sure exactly what characters do or do not need escaping.

Is there a function available in the CRT or somewhere in the linux headers to safely escape a string to pass to the command line ?

Answer Source

There isn't a single solution that works everywhere because different shells have different ideas of what special characters are and how they are interpreted. For bash, you could probably get away with surrounding the entire filename in single quotes after replacing every single quote in the file name with '"'"' (the first single quote stops the sequence, the "'" appends the literal single quote to the string, the final single quote starts the quoted sequence again). A better solution would be to find a way to call the program without using system, such as by using fork with one of the exec functions so there is no shell interpolation.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download