我需要找到一些字符串的位置。这些字符串存储在名为queryfile
的文件中,来自名为datafile
的其他文件。
但是,我的程序没有按预期工作。 有人可以帮助我吗?
我的节目
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
FILE *queryfile;
queryfile = fopen("op2query.txt","r");
FILE *datafile;
datafile = fopen("op2data.txt","r" );
int i = 1;
char word[99];
char search[99];
if(queryfile==NULL) {
printf("Error in reading Query File");
exit(1);
}
if(datafile==NULL) {
printf("Error in reading Data File");
exit(1);
}
while(fscanf(queryfile,"%98s",search)==1){
while(fscanf(datafile,"%98s",word)==1){
if (strcmp(word,search)==0){
printf("\n %i %s ", i, search);
rewind(datafile);
i=1;
break;
}
else
i++;
}
}
fclose(datafile);
fclose(queryfile);
return 0;
}
答案 0 :(得分:2)
我通过将查询字符串拆分为单词来构建要测试的每组单词的数组。这些单词可以跨越数据文件中的换行符。我在集合的第二个单词上标记数据文件位置,如果搜索失败,我会寻找到那一点(如果需要)。即使我复制数据文件中的每个单词“age”,程序也会成功。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXWORDS 5
#define MAXLEN 99
int main()
{
int j, i, done, words, count;
long mark;
char word[MAXLEN];
char search[MAXLEN];
char *tok, *sptr[MAXWORDS];
FILE *queryfile;
FILE *datafile;
if ((queryfile = fopen("op2query.txt","r")) == NULL) {
printf("Error in reading Query File");
exit(1);
}
if ((datafile = fopen("op2data.txt","r" )) == NULL) {
printf("Error in reading Data File");
exit(1);
}
while(fgets(search, MAXLEN, queryfile) != NULL){
words = 0;
done = 0;
count = 0;
mark = -1;
tok = strtok(search, " \r\n");
while (tok && words < MAXWORDS) { // build array of query
sptr[words++] = tok;
tok = strtok(NULL, " \r\n"); // strips newline too
}
if (words < 1) // no more queries
break;
rewind(datafile); // beginning of file
while (!done) { // until none to read
count++;
if (mark >= 0) // when more than one word to search
fseek (datafile, mark, SEEK_SET);
mark = -1;
for (j=0; j<words; j++) {
if (j == 1) // mark for next search
mark = ftell(datafile);
if (fscanf(datafile, "%98s", word) != 1){
done = 1; // end of file
break;
}
if (strcmp(sptr[j], word)!=0)
break; // failed multi word search
}
if (done)
printf("NOT FOUND!");
else if (j == words) { // if all words found
printf("%d", count);
done = 1; // success
}
}
for (i=0; i<words; i++)
printf(" %s", sptr[i]); // show array of words asked
printf("\n");
}
fclose(datafile);
fclose(queryfile);
return 0;
}
节目输出:
18 wisdom
40 season
NOT FOUND! summer
22 age of foolishness
更新 - 在找不到查询时打印NOT FOUND!
。在查询文件中添加了“summer”。
答案 1 :(得分:0)
你应该把一些调试输出放在fscanf调用之后(比如printf("search:<%s> word:<%s>", search, word);
然后你会看到,fscanf在找到一个白色空间时停止了。您将wisdom
与op2data.txt中的每个连续单词进行比较。
您应该逐行阅读fgets()
从搜索中删除CR / LF。
但请注意,数据文件中的多字搜索字可以在行之间分割。像:
find me
i am the text to find
me in this file
所以更好的解决方案是: