从 C 中的 fgets() 修剪尾随的 \0
Trimming a trailing \0 from fgets() in C
我正在用 C 编写一个简单的 shell 程序,该程序在命令行中接受来自用户的命令,将输入标记化到数组中,然后使用 execvp() 函数执行用户命令。要读取用户输入,我正在使用 fgets() 函数:
char command[MAX];
fgets(command, MAX, stdin);
现在这是我的问题所在(而且我对 C 编程还很陌生)。例如,如果用户键入 ls -af 并且我检查键入的字符串的长度,如
strlen(command)
即使只输入了 6 个字符,结果还是 7。我知道这是因为 fgets() 总是在字符串末尾添加 \0。但是,这会在以后给我的程序带来问题。我使用 strtok() 函数标记输入,如下所示:
char* token;
int i = 0;
char* args[10];
token = strtok(command, " ");
while(token != NULL)
{
args[index] = token;
token = strtok(NULL, " ");
index ++ ;
}
args[index] = NULL;
在此之后,args 数组中 NULL 之前的最后一个元素(在本例中为 -af)保留由 fgets() 生成的尾随 \0。这反过来会导致我的 execvp() 调用出现问题,因为它无法识别数组中的最后一个元素。我假设它读作 -af[=21=] 而它应该只是 -af。有没有办法 trim 由 fgets() 函数产生的最后一个 \0 或者有没有更简单的方法来读取用户的输入?提前致谢!
如上面的评论所述,您可能会看到换行符存储在字符串中。
正在阅读 MAN (3) page for fgets(强调我的):
fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte ('[=11=]') is stored after the last character in the buffer.
如果你想去除换行符,你可以看到 this post 有一个答案建议你使用这样的东西:
buffer[strcspn(buffer, "\n")] = 0;
我正在用 C 编写一个简单的 shell 程序,该程序在命令行中接受来自用户的命令,将输入标记化到数组中,然后使用 execvp() 函数执行用户命令。要读取用户输入,我正在使用 fgets() 函数:
char command[MAX];
fgets(command, MAX, stdin);
现在这是我的问题所在(而且我对 C 编程还很陌生)。例如,如果用户键入 ls -af 并且我检查键入的字符串的长度,如
strlen(command)
即使只输入了 6 个字符,结果还是 7。我知道这是因为 fgets() 总是在字符串末尾添加 \0。但是,这会在以后给我的程序带来问题。我使用 strtok() 函数标记输入,如下所示:
char* token;
int i = 0;
char* args[10];
token = strtok(command, " ");
while(token != NULL)
{
args[index] = token;
token = strtok(NULL, " ");
index ++ ;
}
args[index] = NULL;
在此之后,args 数组中 NULL 之前的最后一个元素(在本例中为 -af)保留由 fgets() 生成的尾随 \0。这反过来会导致我的 execvp() 调用出现问题,因为它无法识别数组中的最后一个元素。我假设它读作 -af[=21=] 而它应该只是 -af。有没有办法 trim 由 fgets() 函数产生的最后一个 \0 或者有没有更简单的方法来读取用户的输入?提前致谢!
如上面的评论所述,您可能会看到换行符存储在字符串中。
正在阅读 MAN (3) page for fgets(强调我的):
fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte ('[=11=]') is stored after the last character in the buffer.
如果你想去除换行符,你可以看到 this post 有一个答案建议你使用这样的东西:
buffer[strcspn(buffer, "\n")] = 0;