Frans-Willem Frans-Willem - 6 months ago 30
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 ?


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.