Answer the question
In order to leave comments, you need to log in
The gets function in C. Why doesn't character-by-character comparison work?
At the stage of character-by-character comparison, the program gives an error. What to do?
#include <stdio.h>
#include <stdbool.h>
int main() {
char sim1, sim2, n;
bool ni = false;
//открываем текстовые файлы//
FILE *txt1;
txt1=fopen("txt.txt","r");
FILE *txt2;
txt2=fopen("txt2.txt","r");
FILE *txt3;
txt3=fopen("txt3.txt","w");
//тестим на предмет их наличия//
if (!txt1 || !txt2 == NULL) {
printf ( "I can't open a file for reading \n" );
return 1;
}
if(!txt3==NULL) {
printf( "I can't open a file for writing \n");
return 1;
}
printf ( "txt1 and txt2 files are open \n");
// посимвольно сравниваем txt1 и txt2//
while(txt1 && txt2) {
txt1=fgets(sim1);
txt2=fgets(sim2);
if(sim1 == sim2)
fputc(sim1,txt3);
else
ni = true;
}
if(ni==false) {
// сообщение о успехе
printf ( "The file contents are identical \n" );
} else {
// Если посимвольное сравнение не увенчалось успехом
printf ( "The contents of the files are not identical \n" );
}
// закрываем файлы
fclose(txt1);
fclose(txt2);
fclose(txt3);
printf ( "End of program" );
return 0;
}
Answer the question
In order to leave comments, you need to log in
What is actually written here?
First txt1 is FILE*. Then, for some reason, txt1=fgets(sim1), that is, what is assigned to a variable of type FILE*? I advise you to look at the description of fgets in the documentation:
char *fgets(char *s, int size, FILE *stream);
Assigned to char*. And from where, from what file?
I think it meant:
sim1=fgetc(txt1);
Then it makes some sense.
Further, while over txt1 && txt2 makes no sense - the pointers will be non-null even when the end of files is reached. It is more correct to wrap it in such a cycle:
while(!feof(txt1) && !feof(txt2)) { ... }
At the end, check that feof(txt1) && feof(txt2), otherwise one of the files is over, and the second is not - the sizes do not match, the files are different.
And it is more correct to do block reading using fread and memcmp, it is much more efficient in terms of speed (yes, of course, the difference is imperceptible for small files, but still):
int isequal=1;
while(!feof(txt1) && !feof(txt2)) {
char buf1[1024];
char buf2[1024];
int readsize1 = fread(buf1, 1, 1024, txt1);
int readsize2 = fread(buf2, 1, 1024, txt2);
if (readsize1 != readsize2) {
isequal=0;
break;
} else {
if (memcmp(buf1, buf2, readsize1)) {
isequal=0;
break;
}
}
if(isequal) {
// одинаковы
} else {
// отличаются
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question