我正在写一个C程序来读取文件并检查里面是否有给定的句子。如果给定句子存在于文件中,该函数必须分别返回“找到”或“未找到”。句子被一个/符号分开。C程序为了在文件中找到给定的句子
Example of file:
1,2,3,4/
car, house, hotel/
2,age,12/
1,2/
1,2,3,5/
house, car/
Example of word to look for:
1,2/
我的想法是每次冒了一句,从该文件,并把它放在一个阵列(称为元),检查阵列(元)等于阵列(称为句子)包含给定我正在查找的句子,并将该数组(ary)重新用于文件中的下一句。
我写这段代码:
#include <stdio.h>
void main()
{
char *sentence;
FILE *my_file;
char *ary;
int size = 500;
int got;
int ind=0;
int rest;
int found=0;
sentence="1,2";
my_file=fopen("File.txt", "r");
if(my_file==NULL)
{
printf("I couldn't open the file\n");
}
else
{
ary = (char*)malloc(500*sizeof(char));
while((got=fgetc(my_file))!=EOF)
{
if(got!='/')
{
ary[ind++]=(char)got;
}
else
{
ary[ind++]='\0';
rest = compare(sentence,ary);
if(rest==0)
{
found =1;
printf("found\n");
return;
}
ind=0;
free(ary);
ary = (char*)calloc(500, sizeof(char));
}
}
if(found==0)
{
printf("not found\n");
}
fclose(my_file);
}
}
int compare(char str1[], char str2[])
{
int i = 0;
int risp;
if(str1>str2 || str1<str2)
{
risp=-1;
}
if(str1==str2)
{
while(str1[i++]!='\0')
{
if(str1[i]!=str2[i]) risp=1;
}
}
return risp;
}
它编译,但不能正常工作,我不找出原因。
我试过另一种解决方案,更简单,但不起作用。
void main()
{
char sentence[]="1,2";
FILE *my_file;
char string[2000];
int ind=0;
int rest;
int trovato = 0;
int got;
my_file=fopen("File.txt", "r");
if(my_file==NULL)
printf("I couldn't open the file\n");
else
{
string[0]='\0';
while((got=fgetc(my_file))!=EOF)
{
if(got!='/')
{
string[ind++]=(char)got;
}
else
{
string[ind++]='\0';
rest = compare(sentence, string);
if(rest==0)
{
found =1;
printf("found\n");
return;
}
ind=0;
//delete the array
int x=0;
while(string[x]!='\0')
{
string[x]='\0';
x++;
}
}
}
if(found==0) printf("not found\n");
fclose(my_file);
}
}
有人能指出我的错误还是让我知道更好的解决方案? 谢谢。
“它不能正常工作”是什么意思? “不能正常工作”和“不能工作”除非你告诉我们他们的意思,否则没有任何意义。我们无法从我们所在的位置看到您的屏幕,并且我无法从我现在的位置完全阅读您的想法。请具体说明一下 - 您张贴了大量代码以显示您尝试过的内容,这很好,但是如果您希望我们提供帮助,则需要告诉我们该代码存在什么问题。 :-) – 2013-03-09 05:07:38