私はファイルを読んで、その中に与えられた文があるかどうかをチェックするために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と呼ばれる)に入れ、配列(ary)が私が探している特定の文を含む配列(文と呼ばれる)と等しいかどうかを確認することです、ファイル内の次の文にその配列(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);
}
}
誰かが私の間違いを指摘したり、より良い解決策を教えてもらえますか?ありがとうございました。