I'm trying to create a program that reads a text file and that grabs the first line and second line with fgets() storing them into separate arrays for comparison with strcmp() and then running that in a loop to go to the 2nd and 3rd line store it in character array then compare and repeated this process with all the lines until the end of file. I need help in how to do it using a for loop. This is my a.txt file:
Hello?
Hello?
Hello?
No answer? Let's try again:
Hello?
Tik
Tok
Tok
tok
This is what I'm getting back when I compile:
dup
L1 Hello?
L2 Hello?
dup
L1 Hello?
L2 Hello?
no dup
L1 Hello?
L2
no dup
L1 Hello?
L2
no dup
L1 Hello?
L2 No answer? Let's try again:
dup
L1 Hello?
L2 Hello?
no dup
L1 Hello?
L2 Tik
no dup
L1 Hello?
L2 Tok
no dup
L1 Hello?
L2 Tok
no dup
L1 Hello?
L2 tok-----
this is the file name:a.txt
Not sure why its repeating Hello's instead of going to the next line Do I have to clear the array somehow? Any help would be awesome, thanks!
--I only inserted relevant code to this post, this isn't all of the code just fyi
char * filename = argv[argc-1];
FILE *f;
f = fopen(filename, "r");
if(f == NULL)
{
fprintf(stderr, "unable to open file\n");
return 1;
}
char line1[MAX_CHAR_FOR_LINE_INPUT];
char line2[MAX_CHAR_FOR_LINE_INPUT];
for (char * j = fgets(line1, MAX_CHAR_FOR_LINE_INPUT,f); j != NULL; j = fgets(line1, MAX_CHAR_FOR_LINE_INPUT,f) ){
for (char * n = fgets(line2, MAX_CHAR_FOR_LINE_INPUT,f); n != NULL; n = fgets(line2, MAX_CHAR_FOR_LINE_INPUT,f) ){
int value = strcmp(line1,line2);
if ( value == 0 ){
printf("dup\n");
}
else{
printf("no dup\n");
}
printf("%s",line1);
printf("%s",line2);
}
printf("-----\n");
}