cstringchar

How to compare two strings in C with the number of characters compared being the number of characters in a string received from a file


I am trying to create a "bank" program in C which has unique logins and to do so, I have a file of usernames and check if the username entered by the user matches a pre-existing one and have done so below

    FILE *pF = fopen("usernames.txt", "a+"); //opens 2nd file to read it, and creates it if it doesn't exist
    
    //int length = sizeof(userName) / sizeof(userName[0]);
    while (fgets(buffer, 255, pF)) { //reads file adn checks if the username is on it
        if (strncmp(buffer, userName, strlen(userName)) == 0) { //checks the amount of characters in the string userName and only compares those characters
            uniqueUsername = false;
            break;
        }
    }

However my issue is that if a pre-existing username such as "Daniel" exists, you can't create "Dan" as another username.

I have tried changing strlen(userName) into strlen(buffer) but that compares all 255 characters of the buffer string (I created it as a dummy array of 255 bytes) and results in a no match. Are there any ways to overcome this issue?


Solution

  • If the file contains the user names without leading or trailing spaces, one per line, you can just verify that in addition to a match with strncmp, the next character is a newline '\n'.

    Here is a modified version:

    // check user name against the list of user names
    // return -1  if the file cannot be open
    // return 0   if the userName already exists
    // return 1   if the userName was appended
    int check_username(const char *userName) {
        char buffer[256];
        int uniqueUsername = 1;
        size_t len = strlen(userName);
        FILE *pF = fopen("usernames.txt", "a+");
        if (pF == NULL)
            return -1;
        while (fgets(buffer, sizeof buffer, pF)) {
            if (!strncmp(buffer, userName, len) && buffer[len] == '\n') {
                uniqueUsername = 0;
                break;
            }
        }
        if (uniqueUsername) {
            // append the unique user name
            fprintf(pF, "%s\n", userName);
        }
        fclose(pF);
        return uniqueUsername;
    }