gpt4 book ai didi

C - 读取多个文件流

转载 作者:太空宇宙 更新时间:2023-11-04 03:36:12 25 4
gpt4 key购买 nike

我正在编写我自己的经典 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;

}

最佳答案

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

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

在你的循环中。

关于C - 读取多个文件流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32540886/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com