问题
int bytes_read;
int rv;
int nchars = 200; /*max possible number for the input of the user*/
size_t nbytes = nchars; /*size of chars in bytes*/
char *commands[2];
char *line = malloc(nbytes + 1);
bytes_read = getline(&line, &nbytes, stdin); /*read line from stdin*/
if (bytes_read == -1) {
printf("Read line error");
exit(-1);
} else {
if (line[strlen(line-1)] == '\n') {
line[strlen(line-1)] = '\0'; /*change new line character in the end of the line of stdin*/
}
}
if (strcmp(line,"exit") == 0) {
rv = 3;
exit(rv);
}
commands[0] = line;
commands[1] = NULL;
execvp(commands[0], commands);
perror("Execution error");
exit(-1);
I have a problem in the code above. If i use getline or even fgets to get input from the user from the terminal, and type "ls" for example execvp prints that there is "no such file or directory". But If I put commands[0]="ls" it runs correctly. What could be the reason?
回答1:
if (line[strlen(line-1)] == '\n') {
line[strlen(line-1)] = '\0'; /*change new line character in the end of the line of stdin*/
That logic to remove the '\n' looks incorrect. I think it should be:
if (line [ strlen(line) - 1 ] == '\n' )
line [ strlen(line) - 1 ] = '\0'; /*change new line character in the end of the line of stdin*/
来源:https://stackoverflow.com/questions/12468994/char-array-and-getline-in-c