C - 读取多个文件流

C - reading multiple file streams

我正在编写我自己的经典 UNIX 程序的简化版本 'wc'(字数统计)。它计算行数、单词数和字符数。所有这些功能都可以正常工作。但是我 运行 遇到麻烦的地方是我试图从 *argv[x] 读取多个文件。我需要把每个变量都做成一个数组,运行整个过程通过循环来实现我想要的。

我的程序returns一个段错误。在代码中的某个时刻,有些东西没有被分配到数组中,我似乎无法弄清楚它到底在哪里。

非常感谢任何帮助:)

/*
 *      [PROGRAM]   wc (word count)
 *       [AUTHOR]   Jesper M. Olsen @ jm0.codes
 *         [DATE]   September 9th 2015
 *      [PURPOSE]   Returns number of lines, words, and characters in a file
 *
 *  [DESCRIPTION]   This program is meant to be utilized as a handy little browsing tool.
 *                  For instance, while moving through the filesystem of a programming archive,
 *                  just type 'wc <filename>' and you will get number of lines, words and characters returned promptly.
 */

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

int main(int argc, char *argv[])
{
    if (argc == 1)
        return -1;

    int numL[argc]; /* initialize array value placeholders */
    int numW[argc];
    int numC[argc];
    int getC[argc];
    int getW[argc];

    int setNull;
    for (setNull = 1; setNull <= argc-1; setNull++) { /* assign ZERO to value placeholders */
        numL[setNull] = 0;
        numW[setNull] = 0;
        numC[setNull] = 0;
        getW[setNull] = 0;
    }

    int x;
    FILE *fOp[argc-1];
    for (x = 1; x <= argc-1; x++) { /* open file stream for each file */
        fOp[x] = fopen(argv[x], "r");
        if (fOp[x] == NULL)
            return -1;
    }

        int y;
        for (y = 1; (getC[y] = getc(fOp[y])) != EOF; y++) {
            if (getC[y] == '\n') numL[y]++;
            if (getC[y] == ' ' || getC[y] == '\n' || getC[y] == '\t') getW[y] = 0;
            else if (getW[y] == 0) { 
                getW[y] = 1;
                numW[y]++; 
            } numC[y]++;
        } 

        int z;
        for (z = 1; z <= argc-1; z++) { /* close files */
            fclose(fOp[z]);
        }

    int c;
    for (c = 1; c <= argc-1; c++) {
        printf("[%s] %dL %dW %dC\n", argv[c], numL[c], numW[c], numC[c]);
    }

    return 0;

}   

我认为问题可能是 这里 -

 for (y = 1; (getC[y] = getc(fOp[y])) != EOF; y++) {
        if (getC[y] == '\n') numL[y]++;
        if (getC[y] == ' ' || getC[y] == '\n' || getC[y] == '\t') getW[y] = 0;
        else if (getW[y] == 0) { 
            getW[y] = 1;
            numW[y]++; 
        } numC[y]++;
    } 

因为数组可以 argc 个元素,但是通过这个循环,您可能已经在 getC 中读取和存储了超过 argc 的整数。从而得到 Seg Fault

但我们不知道文件中的内容我们无法确定。

尝试增加数组的大小。

注意 - 最好从索引 0 开始初始化数组。在此代码中,您没有使用索引 0.

这将在您到达最后一个文件时导致段错误

FILE *fOp[argc-1];

for (x = 1; x <= argc-1; x++) { /* open file stream for each file */
    fOp[x] = fopen(argv[x], "r");
    if (fOp[x] == NULL)
        return -1;
}

因为数组不够大。应该是

FILE *fOp[argc];

使用

更容易发现错误
< argc

而不是

<= argc-1

在你的循环中。