首页 > 解决方案 > 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);
        }
    }

}

标签: c

解决方案


编辑您的代码:

#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.

鼓励您将一行字符串拆分为单词并在单词列表中搜索该字母。


推荐阅读