Extra empty string when parsing a string in arguments

I am trying to use the following parsing function that I found on the internet:

    void  parse(char *line, char **argv)
    {
         while (*line != '\0') {       /* if not the end of line */ 
              while (*line == ' ' || *line == '\t' || *line == '\n')
                   *line++ = '\0';     /* replace white spaces with 0    */
              *argv++ = line;          /* save the argument position     */
              while (*line != '\0' && *line != ' ' &&  *line != '\t' && 
              *line != '\n') 
                   line++;             /* skip the argument until ...    */
         }
         *argv = '\0';                 /* mark the end of argument list  */
    }

      

And it works very well for what I want to do (creating my own char ** argv), but it has one drawback. It creates an extra blank line in my argv after my last argument and before my NULL. Can any of you see where I can change the code to fix this? I've tried going through gdb but I can't seem to figure it out.

Example. If my line is simply "1"

, *argv =[1, , (null)]

. I need to get rid of this blank line.

I tried to change the white space directly, but that doesn't work. For example, I've tried:

   char **temp = args;
   int count =0;
   while(*temp != NULL){
      *temp = *(temp +1);
      count++;}
    args[count] = NULL;

      

+3


source to share


1 answer


Your code will contain an empty string (which is not well characterized as "white space") at the end of the argument list if the string it points line

to ends in a space. You can avoid this by first truncating any trailing spaces (spaces, tabs, and / or newlines), reading line

in such a way as to avoid any possibility of such a closing space being included, or by force-formatting whitespace and changing the penultimate line to *--argv = '\0'

.



While I'm at it, I notice that while '\0'

it is actually a perfectly valid null pointer expression, it is nevertheless much less clear than a macro, NULL

or even in this case plain 0

.

+3


source







All Articles