我的代码有问题,我试图在文件中搜索一个字符串,我可以读取它,但是,当我比较两个字符串时,它只将文件的最后一个与第一个字符串相等使用 scanf()
输入。
想象一下,我在文件中写了三个词,每个词都返回到该行。
test
test12
test123
如果在我的 scanf()
中我写了 test12
或 test
当它要读取时它将返回 false 到比较所以(!== 0)。但是如果我写 test123
它会起作用,因为它是文件的最后一个字,但我不知道为什么?
char word[26];
char singleLine[26];
FILE *file = fopen("bin/Release/myWords.txt", "a+");
scanf("%26s", word);
if (file != NULL) {
while (!feof(file)) {
fgets(singleLine, 26, file);
compare = strcmp(singleLine, word);
if (compare == 0) {
printf("\n%s\n",word);
}
}
fclose(file);
}
最佳答案
你的程序只能在非常特殊的情况下工作并且有几个问题:
-
scanf("%26s", word);
最多可能影响目标数组中的 27 个字节,其定义的长度仅为26
. - 此外,您应该检查返回值以避免在无效输入时出现未定义的行为。
-
fopen("bin/Release/myWords.txt", "a+");
以附加模式打开文件:这是必要的吗? -
while (!feof(file))
总是错误的,你应该检查fgets()
的返回值返回NULL
在文件末尾。 -
compare = strcmp(singleLine, word);
只比较整行的精确数学,只有当单词有 25 个字符时才会发生,否则singleLine
中的尾随换行符会导致比较失败。此外,断行可能会导致意外结果,以及文件未以换行符结尾的情况。 - 它匹配文件中最后一个词的原因是你忘记在文件中最后一个词后写一个尾随换行符,所以最后一个
fgets()
用确切的单词填充缓冲区,没有尾随换行符。 - 如果您在行内搜索匹配项,您应该使用更大的缓冲区并搜索
strstr
的匹配项. - 如果您搜索完全匹配,您应该在比较之前去掉尾随的换行符。
修改后的版本:
#include <stdio.h>
#include <string.h>
int main() {
char word[27];
char singleLine[256];
FILE *file = fopen("bin/Release/myWords.txt", "r");
if (scanf("%26s", word) != 1)
return 1;
if (file != NULL) {
while (fgets(singleLine, sizeof singleLine, file)) {
singleLine[strcspn(singleLine, "\n")] = '\0'; // strip the newline if any
compare = strcmp(singleLine, word);
if (compare == 0) {
printf("\n%s\n", word);
}
}
fclose(file);
}
return 0;
}
关于C如何在文件中搜索字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53401808/