views:

289

answers:

4

Hello,

I'm using this simple C code:

char * command = NULL;
sprintf (command, "ls %s", folderpath);
system(command);

The problem is when the folder name has a space in it... I know that in Unix I need to add a "\", for example ls my\ folder\ name

How can I get around this ? Thank you!

+1  A: 

Use fork() and exec*() instead.

Ignacio Vazquez-Abrams
How does that address his problem, besides making things more complicated?
anon
@Neil: You can specify the arguments manually in an array instead of adding quotes and praying that it doesn't turn things pear-shaped. Obviously just the fork() and exec*() isn't enough, but it should lead one on to find wait*().
Ignacio Vazquez-Abrams
+1  A: 

Simple way out is to put the folder name inside single quotes - sprintf( command, "ls '%s'", folder );. Watch out for command injection as @ndim reminds us.

Nikolai N Fetissov
Brilliantly easy and will work until someone provides you with a *folderpath* of, say, "';cd;rm -rf *".
ndim
Yep, command injection is always fun :)
Nikolai N Fetissov
+1  A: 

If you do this:

char * command = NULL;
sprintf (command, "ls %s", folderpath);

you are in undefined behaviour land. You need to allocate some memory to command:

char command[1000];    // for example
sprintf (command, "ls %s", folderpath);
anon
+2  A: 

If your specific problem is really to get a list of filenames in a folder, you'd be better off using the system calls opendir/readdir/closedir instead. See their manual pages for details.

Lars Wirzenius