C文件IO问题。程序未按预期运行。

时间:2014-11-22 18:45:33

标签: c file-io

我正在做一些家庭作业,我需要写的一个功能应该通过一个代表字典的文本文件来查看,并用我找到的单词数量更新结构,最短的单词和最长的单词字。

然而,当我尝试运行该程序时,它只是在命令提示符中暂停一段时间,就好像我处于无限循环中一样。

int info(const char *dictionary, struct DICTIONARY_INFO *dinfo)
{
  /* Variable Declarations                                                 */
  FILE *fp;                     /* Pointer to the file being opened        */
  char str[21] = {0};           /* Char array to hold fgets                */
  unsigned int longest_length;  /* Length of the longest word in the dict  */
  unsigned int shortest_length; /* Length of the shorest word in the dict  */
  int number_words;             /* Number of words in dict                 */

  longest_length = 0;
  shortest_length = 21; 
  number_words = 0;

  /* Opens the file                                                        */
  fp = fopen(dictionary, "rt");

  /* If the file was successfully opened                                   */
  if(fp)
  {
    /* While we're not at the end of the file                              */
    while(!feof(fp))
    {
      /* If we can successfully get a line with fgets                      */
      if(fgets(str, strlen(str), fp))
      {
        /* Replaces the NL char with a null 0.                             */
        my_nl_replace(str);

        /* If the length of this word is longer than our current longest   */
        if(strlen(str) > longest_length)
          longest_length = strlen(str);

        /* If the length of this word is shorter than the current shortest */
        if(strlen(str) < shortest_length)
          shortest_length = strlen(str);

        ++number_words;
      }
    }

    /* Closes the file, since we're done using it                          */
    fclose(fp);

    /* Modifies the dictionary struct with the info just collected         */
    (*dinfo).shortest = shortest_length;
    (*dinfo).longest = longest_length;
    (*dinfo).count = number_words;
    return FILE_OK; 
  }

  /* If the file was not successfully opened                               */
  else
  {
    return FILE_ERR_OPEN;
  }
}

如果有人好奇,nl_reaplace的内容如下:

void my_nl_replace(char *string)
{
  string[(strlen(string))] = '\0';
}

1 个答案:

答案 0 :(得分:1)

在你编写strlen(str)的地方,它会转换为零,因为str被初始化为以零开头,因此是一个空字符串。您将重复读取零个字符,因为您从未读过该文件中的任何字符,您将永远不会达到EOF,因此您将永远循环。

您应该做的是将当前位置保存在文件中,读取一定数量的字符(在您的情况下为21),从缓冲区读取第一个字的长度并将位置重置为之前的位置,再加上你读的这个词的长度。有关如何执行此操作,请参阅fseek()