Sto cercando di allenarmi in c, il mio goal è leggere il e controllare se c'è una data frase all'interno. La funzione deve ritornare "found" o "not found" rispettivamente se la data frase è all'interno del file o no.
Le frasi sono divise dal simbolo "/".
Esempio di file:
1,2,3,4/
car, house, hotel/
2,age,12/
1,2/
1,2,3,5/
house, car/
Esempio di frase da cercare:
1,2/
La mia idea è quella di prendere la frase ogni volta, metterla in un array(ary[]) e controllare se l'array è uguale a quello della frase data (sentence[]).
Ho scritto questo codice:
codice:
#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;
}
Compila, ma non funziona.
Qualcuno mi può aiutare a capire l'errore o a trovare una migliore soluzione per favore?
Grazie
P.S.: Avevo provato anche quest'altra versione:
codice:
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);
}
}