我正在寫一個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