以下是实现上述要求的C语言程序示例:
#include
#include
int main()
{
// 指定要查找的单词列表
char words[][10] = {"apple", "banana", "orange", "peach"};
// 打开要读取的文件
FILE *file = fopen("text.txt", "r");
if (file == NULL)
{
printf("无法打开文件");
return 1;
}
char word[20]; // 用于暂存读取的单词
int count[4] = {0, 0, 0, 0}; // 记录各单词出现次数的数组
// 逐行读取文件内容
while (fgets(word, 20, file) != NULL)
{
// 去掉单词末尾的换行符
if (word[strlen(word) - 1] == '\n')
{
word[strlen(word) - 1] = '\0';
}
// 遍历单词列表,检查是否匹配
for (int i = 0; i < 4; i++)
{
if (strcmp(word, words[i]) == 0)
{
count[i]++;
break;
}
}
}
// 输出各单词出现次数
for (int i = 0; i < 4; i++)
{
printf("%s: %d\n", words[i], count[i]);
}
fclose(file);
return 0;
}
在上面的程序中,我们首先指定要查找的单词列表 words[]
,然后打开要读取的文件并检查是否成功打开。在读取每一行的内容时,我们需要先将单词末尾可能含有的换行符去掉,然后遍历单词列表并检查是否匹配