Typically, the input you got from fgets
ends with a newline. Say you got {'l', 's', '\n', '\0'}
as the first four bytes in path
. Then, when parseArgs
has set argv[0]
to point to the first character in path
, the next iteration overwrites the newline with '\0'
, and sets argv[1] = &path[2];
:
void parseArgs(char *path, char *argv[]) {
while (*path != '\0') {
while (*path == ' ' || *path == '\t' || *path == '\n') {
*path++ = '\0';
}
*argv++ = path;
while (*path != '\0' && *path != ' ' && *path != '\t' && *path != '\n') {
path++;
}
}
*argv = '\0';
}
so your argv
array contains a pointer to an empty string between the last real argument and the NULL
terminating the array. Thus ls
tries to list the contents of ""
- which doesn't exist.
Since you can't be certain that the input you got from fgets
ends with a newline, guard the assignment
if (*path) *argv++ = path;
to avoid that.