I'm training myself with c, my goal is to read the file and check if there is a given sentence inside of it. The function has to return "found" or "not found" respectively if the given sentence exists in the file or not.
The sentences are divided by a /
symbol.
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/
My idea is to take each time a sentence from the file and put it in an array (called ary), check if the array (ary) is equal to the array (called sentence) that contains the given sentence that I'm looking for, and reuse that array (ary) for the next sentence in the file.
I've written this code:
#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;
}
It compiles, but doesn't work properly and I don't find out why. Can someone please point out my mistakes or let me know of a better solution?
Edit: When I print the two str that relative to the sentence is ok, but the other one after the first print continues printing with a break in front of the words. Like the following:
Str1:1,2
Str2:1,2,3,4
Str1:1,2
Str2:
car, house, hotel
Str1:1,2
Str2:
2,age,12
Str1:1,2
Str2:
1,2
Str1:1,2
Str2:
1,2,3,5
Str1:1,2
Str2:
house, car
Can be this one of my problem? I tryed to solve it...