I need to compare strings from two text files. While separating the strings using strtok() (for either file), I have a problem while referring to sentences from two files, using strtok(), as they are colliding.
#include <stdio.h>
#include <string.h>
#include <conio.h>
int main()
{
FILE *fp,*fp1,*fp2;
fp=fopen("inp1.txt","r");
fp1=fopen("inp2t.txt","r");
int f;
char *a,*b,*chk;
char buffer[500],buf[5000];
while(fgets(buf,5000,fp1));
{
chk= (char *)strtok (buf," ");
while(chk!=NULL)
{
rewind(fp);
f=0;
while(fgets(buffer,500,fp))
{
a= (char *) strtok(buffer,"\t");
b= (char *) strtok(NULL,"\n");
if(stricmp(a,chk)==0)
{
printf("%s",b);
printf(" ");
f=1;
}
}
if(f==0)
{
printf("%s",chk);
printf(" ");
}
chk= (char *) strtok(NULL," ");
}
}
fclose(fp);
fclose(fp1);
getch();
return 0;
}
How can I fix this code so that I’m able to extract tokens from both input files?
strtok() uses global internal values, which will collide. Use strtok_s() to prevent that, as that function takes a reference variable that will keep the two instances separate.