【发布时间】:2015-11-17 12:41:12
【问题描述】:
我正在读取一个大文本文件,其中包含一个字符串,后跟一个换行符。我正在使用 fgets 读取每个字符串并将它们存储在 2D 字符串数组中,并使用 malloc 来分配内存。
void read_file (char **dictionary, char * argv[])
{
FILE * file_name;
int i = 0, word_count = 0, c;
file_name = fopen(argv[0], "r");
if (file_name == NULL)
{
printf("Cannot open file");
}
while (fgets(dictionary[i], MAX_WORD_LENGTH, file_name))
{
dictionary[i][strlen(dictionary[i]) - 1] = '\0';
word_count++;
i++;
}
printf("\n%d words scanned in from: %s\n", word_count, argv[0]);
fclose(file_name);
}
char ** AllocateDictionaryMemory (void)
{
int i;
char **p = malloc(MAX_WORDS * sizeof(*p));
for (i = 0; i < MAX_WORDS; i++)
{
p[i] = malloc(MAX_WORD_LENGTH + 1);
}
if (p == NULL)
{
printf("Failed to allocate 2D string array space\n.");
}
return p;
这使用固定值 MAX_WORD_LENGTH (10)。但是,我现在想用不固定大小的单词来做这件事,这是通过在给出的文本文件中找到最长的单词来决定的。我也有在字典中查找最长单词的功能。问题是 malloc 函数需要给它最大字长,而 read_file 函数需要一个字典数组来读入——这两者都发生在我可以运行查找最长单词函数之前。
我想问题是 - 在我为字典分配空间之前,以及在将实际文本文件读入字典之前,如何在文本文件中找到最长的单词。
我知道我可以将 max_word_length 设置为大得离谱的值,但这有点不合时宜 - 我希望在找到最大字长后确定空间的大小。
read file --> find longest word --> malloc space big enough for the longest word --> read file into new space 是目标。
【问题讨论】:
-
请缩进代码。
-
在我看来是缩进的? :s