-1

嗨,我正在用 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 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)));
4

1 回答 1

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'。)

希望你有这个想法。

于 2013-03-13T02:03:32.257 回答