开发者

How to parse a folder path with spaces in C code

I'm using this simple C code:

char * command = NULL;
sprintf (command, "ls %s", folderp开发者_运维知识库ath);
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!


Use fork() and exec*() instead.


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.


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.


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜