c - 如果 .txt 文件中存在某个单词,则将该单词复制到另一个 txt 文件

标签 c file

TODO:如果 .txt 文件中存在某个单词,将该单词复制到另一个 txt 文件

问题:在“from.txt”中找到的单词不会写到“to.txt”。

错误:

这一行:while ((fscanf(ifp, "%s", line)) != EOF)

代码:

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

#define MAX_LINE 256

void main()
{
    FILE *ifp;
    FILE *ofp;
    char line[MAX_LINE];
    char word[MAX_LINE];
    if ((ifp = open("from.txt", "r")) == NULL)
    {
        printf("Can't open input file.");
        exit(1);
    }
    if ((ofp = open("to.txt", "w")) == NULL)
    {
        printf("Can't open output file.");
        exit(1);
    }
    printf("Enter your word: ");
    gets(word);
    while ((fscanf(ifp, "%s", line)) != EOF)
    {
        if (strcmp(line, word) == 0)
        {
            fputs(line, ofp);
            break;
        }
    }
    fclose(ifp);
    fclose(ofp);
    getch();
}

最佳答案

您使用了错误的 API 来打开文件。您使用的 API -- open -- 用于低级别的、基于描述符的访问。您将从中得到一个 int 值,而 ifpofp 将不正确。

您必须使用名为 fopen 的基于流的 API。它返回一个指向 FILE 结构的指针,您可以将其传递给 fscanf() 等。

非常重要:使用所有编译器警告编译此程序并观察输出。我很确定您已经从编译器收到了警告消息日志。

关于c - 如果 .txt 文件中存在某个单词,则将该单词复制到另一个 txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36091890/

相关文章:

c - Linux 3.0 : "glibc detected" abort - tuning corruption detected feature?

c - C中常量的正则表达式

c - 我如何同步——使原子——从两个进程写入一个文件?

c - 为 Linux 内核搜索 tcp 的滑动窗口协议(protocol)实现

file - 一个文件中的结果与不同文件之间的 VSCode 超链接 :line

在R中读取arff文件

c - "Animated"文本输出

javascript - 是否可以使用 javascript 读取文件?

file - 保存在 iframe 中加载的 PDF 文件

file - 获取给定文件夹名称下的所有文件名