c - C程序在文件中查找包含字母的单词
问题描述
我想编写一个程序来打印文本文件中包含字母(例如“D”)的所有单词。
这是我想出的,但它不起作用。
我得到核心转储错误。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_SIZE 1000
int findWord(FILE *file , const char *letter);
void main()
{
FILE *file;
char path[100];
char letter[1];
printf("Enter file path: ");
scanf("%s", path);
printf("Enter letter to search in file: ");
scanf("%s", letter);
file = fopen(path, 'r');
if (file == NULL)
{
printf("Unable to open file.\n");
printf("Please check you have read/write priveleges.\n");
exit(EXIT_FAILURE);
}
findWord(file, letter);
fclose(file);
return 0;
}
int findWord(FILE *file, const char *letter)
{
char str[BUFFER_SIZE];
while ((fgets(str, BUFFER_SIZE, file)) != NULL)
{
if (str == letter)
{
printf(letter);
}
}
}
解决方案
编辑您的代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define BUFFER_SIZE 1000
int findWord(FILE *file , const char letter);
int main()
{
FILE *file;
char path[100];
char letter;
// const char *fpath = "/home/kozmotronik/Belgeler/karalama.txt";
printf("Enter file path: ");
// fgets(path, sizeof(path), stdin);
// printf("Entered file path: %s\n", path);
scanf("%s", path);
// flushes the standard input
// (clears the input buffer)
// If we don't do this we cannot get the letter from the input buffer
while ((getchar()) != '\n');
printf("Enter letter to search in file: ");
letter = getchar();
// Validity check
if(letter < '0' || letter > 'z') {
printf("Entered character is not valid\n");
exit(EXIT_FAILURE);
}
file = fopen(path, "r");
if (file == NULL)
{
printf("Unable to open file.\n");
printf("Please check you have read/write priveleges.\n");
exit(EXIT_FAILURE);
}
findWord(file, letter);
fclose(file);
return 0;
}
int findWord(FILE *file, const char letter)
{
char str[BUFFER_SIZE];
while ((fgets(str, BUFFER_SIZE, file)) != NULL)
{
printf("Looking for '%c' in %s\n", letter, str);
char *c = strchr(str, (int)letter);
if (c != NULL)
{
printf("'%c' found in %s\n", *c, str);
}
}
return 0;
}
在源代码的同一目录下,创建一个file.txt 文件并输入文件名。这是程序的输出:
Enter file path: afile.txt
Enter letter to search in file: e
Looking for 'e' in This file contains some text.
'e' found in This file contains some text.
Looking for 'e' in This file is used for testing purposes.
'e' found in This file is used for testing purposes.
Looking for 'e' in This file must be read only.
'e' found in This file must be read only.
这是 afile.txt 文件内容:
This file contains some text.
This file is used for testing purposes.
This file must be read only.
鼓励您将一行字符串拆分为单词并在单词列表中搜索该字母。
推荐阅读
- sql - SQL 任务分配循环
- istio - Istio RouteRules v1alpha3。在哪里存储证书。k8s 的秘密?
- php - Laravel 5.6“无法解析的依赖解析......”在进行依赖注入时
- reactjs - react-redux connect 提供未定义的道具
- probability - 如何按白天对正态分布传感器测量进行建模?
- javascript - 在包装组件之前停止安装 React 高阶组件?
- c - C:从文件中获取以特定字符开头的随机字符串
- mpi - 使用 MPI Barrier 会导致致命错误
- php - 错误:SQLSTATE[HY093]:无效参数号:未定义参数 NOOB
- laravel - 雄辩的 hasOne 关系返回 null