How to parse a folder path with spaces in C code

和自甴很熟 提交于 2019-12-13 05:31:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!