EDIT: I'll leave the question here for other people to read if they have the same problem; I've been adviced in the comments that the solution is line[strcspn(line,"\r\n")]= 0. In my Operating Systems course I was never told of \r, therefore you may have had the same issue and this might be useful to you, too.
So I've already read everything on stack overflow regarding how to get rid of \n carachter after reading from a text file using fgets.
In my C file, I have this written:
const char *ESCAPE= "1a2b3c4e5d";
FILE *FP= fopen(backup.txt);
Assume this is what I've got written in backup.txt: 1a2b3c4e5d\n Mark
As you can see, the first line is actually identical to ESCAPE, weren't it for the \n carachter. Now let's look at the code below, in which I try to identify "1a2b3c4e5d" in the file, and, after removing the \n carachter, do a strcmp:
char line[64];
while(fgets(line, sizeof(line), FP)){
fprintf(stdout, "this is line lenght: %ld", strlen(line));
// It prints 12
line[strlen(line) -1]= 0; // Removing the new_line carachter;
fprintf(stdout, "This is line after getting rid of new_line: %ld\n", strlen(line));
// It prints 11.
fprintf("This is ESCAPE lenght: %ld\n", strlen(ESCAPE));
// It prints 10;
if(strcmp(line, ESCAPE) == 0){
fprintf(stdout, "I'm Here\n");
}
The very first read of fgets will store in line "1a2b3c4e5d\n", which is lenght 12 according to him. Now, I read 10 carachters and the new_line one, which is 11, since the strlen does not count the null terminator. I expected it to be 11, thus the second print, after I removed \n, I expected lenght to be 10, instead it's 11.
This means there's something else inside the buffer, but I really don't understand what it is, and, of course, the strcmp will never be true, due to this misterious 11nth carachter. Do you have any idea what it is? And how can I solve it? Thanks!
I tried to look for every answer on Stackoverflow. Some even suggest using strcspn, which was a nice discover (it even solves some troubling situations with the buffer), but the code does not work in that situation, for some reason. I can't find an answer and therefore I asked this question.