我们可以使用fgets()函数从文件中读取每行,并进一步使用strtok()函数将行分解为单词。然后,我们可以使用strchr()函数检查单词是否包含所需的字母。
示例代码如下:
#include
#include
int main() {
char fileName[] = "sample.txt";
char letter = 'a'; // letter to search for
char line[100];
FILE *file = fopen(fileName, "r");
if (file == NULL) {
printf("Could not open file %s", fileName);
return 1;
}
while (fgets(line, sizeof(line), file)) {
char *word = strtok(line, " ");
while (word != NULL) {
if (strchr(word, letter) != NULL) {
printf("%s\n", word);
}
word = strtok(NULL, " ");
}
}
fclose(file);
return 0;
}
注意,代码中的sample.txt文件应该包含要搜索的文本。