如何使用scanf中的参数填充字符指针数组?

时间:2013-11-25 06:28:22

标签: c arrays shell printf char-pointer

我正在尝试用C编写一个非常基本的shell程序。我面临的问题是尝试使用从输入中获取的单词填充我的argv字符指针数组。当我尝试使用下面的parse()函数填充它时尝试打印出argv数组的内容,我得到了一个分段错误。我知道这意味着我可能正在尝试访问超出范围的argv数组的一部分。但是,即使只提供一个参数来填充数组,我仍然会得到段错误。用于打印argc的printf调用根据输入返回argc的正确值,但第二次使用* argv [0]的printf调用是导致段错误的。我想知道我的错误是否与我试图打印argv的内容有关,或者错误是因为我试图错误地填充argv。

编辑:我应该补充一点,getword()函数接受一行文本并返回由空格分隔的第一个单词以及许多其他分隔符。如果有必要的话,我可以发布所有分隔符,但是我认为这个问题不是因为getword()。

编辑2:在头文件中添加并在main中包含#include语句。

编辑3:在main()下添加了getword函数,在p2.h下添加了getword.h

这是p2.h,头文件包含在main:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "getword.h"
#include <signal.h>

#define MAXITEM 100

getword.h:

#include <stdio.h>
#include <string.h>
#include <strings.h>

#define STORAGE 255

int getword(char *w);

int parse(char *, char *[]);

这是主要功能:

#include "p2.h"
int main() {
    pid_t pid, child_pid;
    int argc, inputRedirect;
    char *devNull;
    devNull = (char *) malloc(10);
    strcpy(devNull, "/dev/null");
    char *argv[MAXITEM];
    char commandLine[STORAGE];


    for (;;) {
        printf("p2: ");
        scanf("%s", commandLine);
        argc = parse(commandLine, argv);
        printf("argc = %d\n", argc);

        if(argc == 0)
            continue;
        printf("*argv = %s\n", *argv[0]);
        child_pid = fork();
        if (child_pid < 0) {
            printf("Cannot fork! Terminating...");
            exit(1);
        } else if (child_pid == 0) {
            inputRedirect = open(devNull, O_RDONLY);
            dup2(inputRedirect, STDIN_FILENO);
            close(inputRedirect);
            execvp(*argv, argv);
        }
        else {
            for(;;) {
                pid = wait(NULL);
                if(pid == child_pid)
                   break;
            }
            printf("Child's pid is %d\n", child_pid);
        }
    }
    killpg(getpid(), SIGTERM);
    printf("p2 Terminated.\n");
    exit(0);
}

int parse(char *commandLine, char *argv[]) {
    int i, argc = 0;
    char *commandPointer = commandLine;
    while (*commandPointer != '\0') {
        *argv = commandPointer;
        argc++;
        getword(commandPointer);
    }
    *commandPointer = '\0';
    *argv = '\0';
    return argc;
}

getword.c:

#include "getword.h"
#include <stdlib.h>

/*Function Prototypes*/
int tilde(char *p, int i);
int BSFollowedByMetaCharacter(int c, char *w);


int getword(char *w) {

    int c;
    int index = 0;

    /*This while loop removes all leading blanks and whitespace characters
     * The if statement then tests if the first character is a new line or
     *  semicolon metacharacter*/
    while ((c = getchar()) == ' ' || c == '\t' || c == '\n' || c == ';') {
        if (c == '\n' || c == ';') {
            w[index] = '\0';
            return 0;
        }
    }

    /*This if statement calls ungetc() to push whatever character was taken
     * from the input stream in the previous while loop back to the input
     * stream. If EOF was taken from the input stream, ungetc() will return EOF,
     * which will then cause getword() to return -1, signalling that it reached
     * the End Of File. */
    if (ungetc(c, stdin) == EOF)
        return -1;

    /*This if statement deals with some of the "non-special" metacharacters.
     * If one of these metacharacters is pulled from the input stream by getchar(),
     * it is stored in w and null-terminated. getword() then returns the length of
     * the current string stored in w. If getchar() pulls anything besides one of the
     * specified metacharacters from the input stream, it is then returned using ungetc() after
     * the if statement.*/
    if ((c = getchar()) == '<' || c == '>' || c == '|' || c == '&') {
        w[index++] = c;
        int d = getchar();
        if (c == '>' && d == '>')
            w[index++] = d;
        else {
            ungetc(d, stdin);
        }
        w[index] = '\0';
        return index;
    }
    ungetc(c, stdin);

    /*This while statement handles plain text from the input stream, as well as a few 'special'
     * metacharacters. It also ensures that the word scanned is shorter than STORAGE-1 bytes.*/
    while ((c = getchar()) != ' ' && c != '<' && c != '>' && c != '|'
        && c != ';' && c != '&' && c != '\t' && c != '\n' && c != '\0'
        && index <= STORAGE - 1) {
        if (c == '~') {
            int *ip = &index;
            index = tilde(&w[index], *ip);
            continue;
        }/*END IF*/
        else if (c == '\\') {
            int d = c;
            c = getchar();
            if (BSFollowedByMetaCharacter(c, w)) {
                w[index++] = c;
                continue;
            } else {
                w[index++] = d;
            }

        }/*END ELSE IF*/
        w[index] = c;
        index++;
    }/*END WHILE*/

    ungetc(c, stdin);/*This final ungetc() call is used to push any meta characters*/
    w[index] = '\0'; /*used as delimiters back to the input stream, to be retrieved*/
    return index;    /*at the next call of getword().                                      */
}/*END getword()*/

int tilde(char *cp, int i) {
    int *ip;
    ip = &i;
    char *p = cp;
    char *o;
    o = (strcpy(p, getenv("HOME")));
    int offset = strlen(o);
    *ip = *ip + offset;
    return i;
}

int BSFollowedByMetaCharacter(int c, char *w) {
    if (c == '~' || c == '<' || c == '>' || c == '|' || c == ';' || c == '&'
        || c == ' ' || c == '\t' || c == '\\') {
        return 1;
    } else {
        return 0;
    }
}

1 个答案:

答案 0 :(得分:0)

getword.c中的功能似乎是正确的。您的问题在于parse

要使用execvpargv的内容应该跟随(输入:“hello world”):

argv[0] -> "hello"
argv[1] -> "world"
argv[2] -> NULL

这里,argv是一个字符指针数组。但是,在parse函数中,您在这里将argv视为简单的字符指针:

*argv = commandPointer;

在这里:

*argv = '\0';

将您的解析功能更改为以下内容:

int parse(char *commandLine, char *argv[]) {
    int argc = 0;
    char *commandPointer;
    argv[argc++] = commandLine;

    do{
        commandPointer = (char*)malloc(sizeof(char) * STORAGE);
        argv[argc++] = commandPointer;
        getword(commandPointer);
    }while(*commandPointer != '\0');
    argv[argc] = NULL;
    return argc;
}

现在,您应该在if-else树之后释放已分配的内存,如:

for(int i = 0; i < argc; i++) free(argv[i]);