C 正在尝试计算缓冲区中的参数数
您好,我正在用C编写一个用于赋值的shell,我不知道如何在我的函数count()中计算并返回缓冲区中的参数数。这就是我目前所拥有的。 提前谢谢C 正在尝试计算缓冲区中的参数数,c,shell,buffer,C,Shell,Buffer,您好,我正在用C编写一个用于赋值的shell,我不知道如何在我的函数count()中计算并返回缓冲区中的参数数。这就是我目前所拥有的。 提前谢谢 #include <stdio.h> #include <string.h> #include <unistd.h> #include <stdlib.h> int count(char* buffer) { int count=0; //COUNT ARGS WITHIN BUFFER
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
int count(char* buffer)
{
int count=0;
//COUNT ARGS WITHIN BUFFER HERE
return count;
}
int main(int argc, char **argv)
{
//buffer is to hold the commands that the user will type in
char buffer[512];
// /bin/program_name is the arguments to pass to execv
//if we want to run ls, "/bin/ls" is required to be passed to execv()
char* path = "/bin/";
while(1)
{
//print the prompt
printf("myShell>");
//get input
fgets(buffer, 512, stdin);
//fork!
int pid = fork();
//Error checking to see if fork works
//If pid !=0 then it's the parent
if(pid!=0)
{
wait(NULL);
}
else
{
int no_of_args = count(buffer);
//we plus one so that we can make it NULl
char** array_of_strings = malloc((sizeof(char*)*(no_of_args+1)));
#包括
#包括
#包括
#包括
整数计数(字符*缓冲区)
{
整数计数=0;
//在此统计缓冲区中的参数
返回计数;
}
int main(int argc,字符**argv)
{
//缓冲区用于保存用户将键入的命令
字符缓冲区[512];
///bin/program\u name是要传递给execv的参数
//如果要运行ls,需要将“/bin/ls”传递给execv()
char*path=“/bin/”;
而(1)
{
//打印提示
printf(“myShell>”);
//获取输入
fgets(缓冲区,512,标准输入);
//叉子!
int-pid=fork();
//检查fork是否工作时出错
//如果pid!=0,则为父级
如果(pid!=0)
{
等待(空);
}
其他的
{
int no_of_args=计数(缓冲区);
//我们加一,这样我们就可以使它为空
char**array\u of_strings=malloc((sizeof(char*)*(no\u of_args+1));
我认为您要计算的是char*缓冲区中以空格分隔的单词数。您可以使用代码:
int i=0;
bool lastwasblank = false;
while (buffer[i] == ' ') i++; //For us to start in the first nonblank char
while (buffer[i] != '\0' && buffer[i] != '\n') {
if (buffer[i] != ' ') {
count++;
while(buffer[i] != ' ') i++;
}
else {
while(buffer[i] == ' ') i++;
}
}
或者类似的东西。这个想法是从字符串缓冲区的开头开始,然后遍历它,每次找到一个单词时添加一个,然后忽略每个字符,直到出现空白,忽略空白,然后再次开始计算单词,直到到达字符串的末尾(通常可以是“\n”,如果用户键入的字符超过512个,则可以是“\0”。)
希望您能理解。sizeof(buffer)/sizeof(buffer[0]);
sizeof
告诉您数据类型的大小,所以这对您没有帮助……非常感谢好的先生!让我试试这个。