【发布时间】:2014-06-03 10:30:34
【问题描述】:
我收到了三个“.txt”文件。
第一个是单词列表。 第二个是要搜索的文档。 第三个是一个空白文档,我的输出将写入其中。
我应该获取第一个文件中的每个单词,搜索第二个文件并将第三个文件中的出现次数打印为“wordX = numOccurences”。
我有一个很好的函数可以返回 wordCount,它会正确返回第一个单词,但我会得到所有剩余单词的零。
我试图取消对所有内容的引用,但我想我已经停滞不前了。 “指针谈话”有问题。
我还没有开始将单词输出到新文件,但是 printf 语句应该是附加模式下的 print to file 语句。很容易。
这是有效的 wordCount 函数 - 如果我只给它一个单词,例如“测试”,它就可以工作,但如果我给它一个我想要迭代的数组,它只会返回 0。
int countWord(char* filePath, char* word){ //Not mine. This is a working prototype function from SO, returns word count of particular word
FILE *fp;
int count = 0;
int ch, len;
if(NULL==(fp=fopen(filePath, "r")))
return -1;
len = strlen(word);
for(;;){
int i;
if(EOF==(ch=fgetc(fp))) break;
if((char)ch != *word) continue;
for(i=1;i<len;++i){
if(EOF==(ch = fgetc(fp))) goto end;
if((char)ch != word[i]){
fseek(fp, 1-i, SEEK_CUR);
goto next;
}
}
++count;
next: ;
}
end:
fclose(fp);
return count;
}
这是我程序的一部分,尝试在循环从第一个文件中获取所有单词时调用该函数。循环正在抓取单词,因为它会打印它们,但 wordCount 不接受第一个单词之外的任何内容。
int main(){
FILE *ptr_file;
char words[100];
ptr_file = fopen("searchWords.txt", "r");
if(!ptr_file)
return -1;
while( fgets(words, 100, ptr_file)!=NULL )
{
int wordCount = 0;
char key[100] = &*words;
wordCount = countWord("document.txt", words);
printf("%s = %d\n", words, wordCount);
}
fclose(ptr_file);
return 0;
}
【问题讨论】:
-
Show
countWordfunction..problem 似乎在那里 -
编辑显示功能
标签: c arrays string pointers io