gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:27:17 24 4
gpt4 key购买 nike

我正在做一些作业,我需要编写的函数之一应该查看代表字典的文本文件,并使用我找到的单词数、最短单词和最长单词更新结构。

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

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';
}

最佳答案

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

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

关于C 文件 IO 问题。程序未按预期运行。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27081090/

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