问题
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:
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.
回答2:
Use fork() and exec*() instead.
回答3:
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.
回答4:
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);
来源:https://stackoverflow.com/questions/2128775/how-to-parse-a-folder-path-with-spaces-in-c-code