cparsingexec

Extra empty string when parsing string into arguments


I'm trying to use the following parsing function I found online:

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 this works really nicely for what I want to do (making my own char **argv), but it has one drawback. It creates an extra empty string 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 stepping through with gdb but I can't figure it out.

Example: If my line is simply "1", *argv =[1, , (null)]. I need to get rid of that empty string.

I've tried directly changing the blank space, but that's not working. For example I've tried:

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

Solution

  • The code you present will include an empty string (which is not well characterized as "an empty space") at the end of the argument list if the string pointed to by line ends in whitespace. You can avoid that by first truncating any trailing whitespace (spaces, tabs, and/or newlines), by reading line in a way that avoids any possibility of such trailing whitespace being included, or by forcing whitespace always and changing the penultimate line to *--argv = '\0'.

    While I'm at it I observe that although '\0' is in fact a perfectly valid expression of a null pointer, it is nevertheless much less clear than the macro NULL, or even, in this case, plain 0.