C - 读取多个文件流

时间:2015-09-12 16:05:46

标签: c segmentation-fault filestream

我正在编写自己的经典UNIX程序的简化版本' wc' (字数)。它计算行数,单词和字符数。所有这些功能都很好。但是当我遇到麻烦时,我试图从* argv [x]中读取多个文件。我需要将每个变量都放到一个数组中,并通过循环运行整个过程来实现我正在寻找的东西。

我的程序返回分段错误。在代码中的某个点上没有将某些东西分配到数组中,我似乎无法确切地知道它在哪里。

非常感谢任何帮助:)

/*
 *      [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;

}   

2 个答案:

答案 0 :(得分:1)

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

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

在你的循环中。

答案 1 :(得分: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多个元素但是使用此循环,您可能在argc中读取和存储的整数超过getC。因此得到 Seg Fault

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

尝试增加数组的大小。

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