Search code examples
cfgetsstrcmp

Strcmp doesn't work on same strings with same length


So, I have this code, where password is a string obtained by breaking into tokens a bigger string, and pass obtained from a text file. I even used strcspn so i can remove '\n' from pass.

    if (ok == 1){

        char buffer[20];
        snprintf(buffer, sizeof(buffer), "%s.txt", username);

        chdir("./passwords") ;

        FILE *userf;
        userf = fopen(buffer,"r");
        if(userf == NULL){
            perror("Eroare la fopen");
            exit(1);
        } else
            printf("Am deschis fisierul cu parola\n");

        char pass[20];

        if(fgets(pass, sizeof(pass), userf) == NULL){

            perror("Eroare la fgets");
            exit(1);
        } 
        pass [ strcspn(pass, "\r\n") ] = '\0'; 
        printf("%s\n%s\n",password, pass);
        printf("%i %i\n",strlen(password), strlen(pass));

        if(strcmp(password, pass) == 0){
            printf("Connected");
        }
    }

As you can see from the terminal it prints out the same string with the same length but strcmp for some reason doesn't return 0.I'm really confused.

enter image description here


Solution

  • If you add a \n to the last printf you'll see it works fine.

    Your program is just exiting before it's flushed the stdout buffer.