2013-04-09 48 views
1

我正在尝试计算文件中每个字的数量。该文件可以是stdin或命令行中提供的文件名(./ count -f)。到目前为止,程序在从命令行读取文件时会提供正确的输出。但是当我试图从标准输入读取时发生错误。程序首先输出正确,然后给出分段错误(核心转储)。这是我的代码的一部分。从标准输入读取的分段错误(核心转储)

FILE * fp; 
int size = 20000; 
char sentence[2000]; // the sentence from stdin 
if (argc != 3) 
{ 
    fgets(sentence,sizeof(sentence),stdin); // read from stdin 
    fflush(stdin); 
    // I think the initialization of word is incorrect, but i do know why it is incorrect 
    char *word = strtok (sentence," !\"#$%&'()*+,./:;<=>[email protected][\\]^_`{|}~\n\t"); 
    while (word != NULL) 
    { 
     get_word(word); // get each word 
     word = strtok (NULL, " !\"#$%&'()*+,./:;<=>[email protected][\\]^_`{|}~\n\t"); 
    } 
} 
else 
{ 
    fp = fopen(argv[2], "r"); 
    if (fp == 0) 
    { 
     printf("Could not open file\n"); 
    } 

      char word[1000]; 
    while (readFile(fp, word, size)) { // let the program read the file 
     get_word(word); // get each word. Works well. 
    } 
} 

get_word功能:

void get_word(char *word){ 
node *ptr = NULL; 
node *last = NULL; 

if(first == NULL){ 
    first = add_to_list(word); // add to linked list 
    return; 
} 

ptr = first; 
while(ptr != NULL){ 
    if(strcmp(word, ptr->str) == 0){ 
     ++ptr->freq; 
     return; 
    } 
    last = ptr;    
    ptr = ptr->next; 
} 
last->next = add_to_list(word); // add to linked list 

}

请帮我弄清楚,为什么我得到一个分段错误(核心转储)。该程序适用于我的Mac,但不适用于Linux。
在此先感谢。

+0

'fflush(stdin)'触发未定义的行为。 get_word是做什么的? – cnicutar 2013-04-09 19:07:20

+0

这不是根本原因,但你不应该调用'fflush(stdin);' - 输入流中未定义fflush。 – Joe 2013-04-09 19:07:49

+0

不,它不是fflush(stdin)问题。我删除它,但仍然得到错误。我认为这是一个记忆问题。该程序适用于我的Mac,但不适用于Linux。 – user605947 2013-04-09 19:11:22

回答

0

问题是

int main (int argc, char *argv[]) { 
    FILE * fp; 

    if (argc != 3) 
    { 
      fgets(sentence,sizeof(sentence),stdin); 
      // and so on 
    } 
    else 
    { 
      fp = fopen(argv[2], "r"); 
      if (fp == 0) 
      { 
        printf("Could not open file\n"); 
      } 
      while (readFile(fp, word, size)) { 
        get_word(word); 
      } 
    } 

    // do some stuff, sorting etc. 

    fclose(fp); 

fclose(fp)无论它是否被打开了。如果fp没有连接到有效的流,则分段错误很常见。很显然,有些实现会优雅地处理fcloseNULL参数,这就是它在Mac上工作的原因。

移动电话fclose进入else分支,而当fopen失败,不只是

printf("Could not open file\n"); 

,但最终的方案。

+0

非常感谢Daniel。大帮助。对此,我真的非常感激。 – user605947 2013-04-09 20:11:46

+0

不客气。帮助(和有趣的谜题)就是我来这里的原因。 – 2013-04-09 20:12:58

0

句子大小是2 kib,而你正在读取stdin的2 kib。之后你使用一个字符串函数。字符串以'\ 0'结尾,但由于您读取了2个没有'\ 0'的kib数据,因此没有字符串结束,所以它是段错误,因为字符串函数(在这种情况下为strtok)可能工作远远超过2亲属。

+0

'fgets' 0-终止它读取的数据。 – 2013-04-09 19:12:38

+0

我只用一个字符测试过它。 – user605947 2013-04-09 19:14:51