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
值,而 ifp
和 ofp
将不正确。
您必须使用名为 fopen
的基于流的 API。它返回一个指向 FILE
结构的指针,您可以将其传递给 fscanf()
等。
非常重要:使用所有编译器警告编译此程序并观察输出。我很确定您已经从编译器收到了警告消息日志。
关于c - 如果 .txt 文件中存在某个单词,则将该单词复制到另一个 txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36091890/