c - 如何在文件中搜索以字符串开头的特定行

标签 c string algorithm

我正在尝试制作这个小程序,需要帮助。

有.txt文件:

namas house
katinas cat
suo dog
skaicius number

我想找到以特定单词开头的一行,然后打印该行的第二个单词。 例如,用户输入单词 katinas。程序查看文件,找到以 katinas 开头的行,最后打印。

我目前拥有的:

int main()
{
    char word;

    printf("Enter your word: ");
    scanf("%s", &word);

    FILE *fp;
    fp = fopen("data.txt", "r+");
    char buffer[256];
    while (fgets(buffer, sizeof buffer, fp) != NULL && atoi(buffer) != word)
    ;
    if (feof(fp))
    {
        printf(&buffer);
    }
    fclose(fp);

    return 0;
}

谢谢。

最佳答案

正如其他地方指出的那样,代码中存在一些错误。这个答案会找到完整的单词,例如“suo”而不是“su”。

#include<stdio.h>
#include<string.h>

int main()
{
    char word[256];                 // adequate string space (not single char)
    char buffer[256];
    char *sptr;
    FILE *fp;
    int found = 0;

    printf("Enter your word: ");
    scanf("%s", word);              // requires a string pointer (note no &)

    fp = fopen("data.txt", "r");    // removed "+"
    if (fp) {
        while (fgets(buffer, sizeof buffer, fp) != NULL) {
            sptr = strtok(buffer, " \t\r\n");
            if (sptr && strcmp(sptr, word) == 0) {
                sptr = strtok(NULL, " \t\r\n");
                if (sptr) {
                    printf("%s\n", sptr);
                    found = 1;
                    break;
                }
            }
        }
        fclose(fp);
    }
    if (!found)
        printf ("%s not found\n", word);
    return 0;
}

关于c - 如何在文件中搜索以字符串开头的特定行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31033451/

相关文章:

c - NaN 作为特殊参数

c - 棘手的数组初始化

python - 将函数应用于列表的任意两个元素 - Python

r - 从 R 中的字符串中提取不同的单词

java - 当必须通过姓名和号码访问时,存储电话簿的最佳数据结构

c - 这种对有效类型规则的使用是否严格遵守?

创建输出文件时更改 .wav 文件头中的字节

c++ - 程序正在跳过 getline ()/C++

c - Knuth 的《编程艺术》第三版和欧几里得算法示例

algorithm - 霍夫曼码 - 压缩