【发布时间】:2014-02-23 19:06:25
【问题描述】:
我目前正在尝试编写一个应用程序来计算 ASCII 文件中单词的出现次数(去除标点符号并忽略空格)。应用程序应将单词和单词计数存储在数据结构中,最终将按降序排序,然后打印到 CSV 文件。
我已开始使用此程序,但在尝试保存新单词时遇到了分段错误。这是我的代码(我知道这不是一个完美的实现,我确实计划改进它):
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <errno.h>
#define TRUE 1
#define FALSE 0
/* This program is designed to take an ASCII input file, count the occurrences of words in it
* and write an output file displaying the data. I intend for it to convert uppercase to
* lowercase, so as not to generate duplicate words in the data structure. It should also
* ignore whitespace and punctuation.
*/
void getWords(void);
void printFile(void);
void save(char *input);
struct word {
char *str;
int wc;
};
struct word *warray = NULL;
FILE *infile;
FILE *outfile;
void getWords(void)
{
rewind(infile);
char cw[100]; // Current word storage
int i = 0, j = 0, c;
while((c = fgetc(infile)) != EOF)
{
if(isalpha(c))
{
if(isupper(c))
{
cw[i] = tolower(c);
++i;
}
else
{
cw[i] = c;
++i;
}
}
else
{
if(c == '\n' || c == '\t' || c == ' ')
{
cw[i] = '\0';
i = 0;
save(cw);
for(j = 0; j < cw[99]; j++)
{
printf("%c", cw[j]);
}
}
}
}
}
void printFile(void)
{
int i, c;
printf("Printing the file to be counted in lowercase...\n");
for(i = 0; (c = fgetc(infile)) != EOF; i++)
{
if(ispunct(c) || isdigit(c))
{
++i;
}
else
{
putchar(tolower(c));
}
}
}
void save(char *input)
{
int exists = FALSE, i = 0;
int elements = sizeof(warray)/sizeof(struct word);
if(!warray)
{
warray = malloc(sizeof(struct word));
printf("Made array.\n");
}
else
{
printf("New.\n");
warray = realloc(warray, (elements++)*sizeof(struct word));
}
while(i < elements)
{
printf("in while loop\n");
if(strcmp(input, warray[i].str) == 0)
{
warray[i].wc++;
}
else
{
++i;
}
}
printf("Out while loop\n");
if(strcmp(input, warray[i].str) == 1)
{
printf("Inside save if statement\n");
warray[elements].str = malloc(strlen(input)+1);
strcpy(warray[elements].str, input);
warray[elements].wc = 1;
elements++;
}
}
int main (int argc, char *argv[])
{
if (argc < 3)
{
puts("Please supply the input filename and desired output filename as arguments.");
return 1;
}
infile = fopen(argv[1], "r");
if(infile == NULL)
{
printf("File failed to open. Error: %d\n", errno);
return 1;
}
else
{
puts("File opened successfully.");
printFile();
getWords();
}
return 0;
}
我已经输入了一些打印语句来尝试隔离问题,它似乎在这里遇到了问题,在 save(char *input) 函数内:
if(strcmp(input, warray[i].str) == 1)
{
printf("Inside save if statement\n");
warray[elements].str = malloc(strlen(input)+1);
strcpy(warray[elements].str, input);
warray[elements].wc = 1;
elements++;
}
我确实有一种感觉,因为我曾要求 strcmp 检查它的值是否 == 1,而我或许应该只检查任何非零值,但我已经尝试过了,我仍然出现分段错误。
如果有人能指出我正确的方向,我将不胜感激,并在此先感谢!
【问题讨论】:
-
第一件事:使用调试器并确定导致错误的行。检查变量并尝试弄清楚它们是如何获得它们的值的。如果需要,请逐步重新运行,观察每一步的变量。如果不确定如何执行上述任何操作,请询问有关这些操作的问题。
标签: c