I am trying to build an authentication system using C programming Language. I have already wrote the code for the functions to take user input (username & password) and to inset it into the database (a .txt
file) in the following formatted way:
ID USERNAME PASSWORD
... ... ...
... ... ...
... ... ...
EOF(just showing the end of the file for the sake or question comprehensibility)
Between each string there is a \t
char.
To make sure the ID (which is pseudo-random generated), the username and the password do not have duplicate inside the database I want to write three functions able to read just the id, just the username and just the password, then compare the result of each with the users input, returning values according to the result of the reading, but I don't know the correct way to do it using low level functions (read(), lseek());
To be sure we are on the same page: I don't want one of you to write code for me, this is unethical and will remove the fun from writing the whole thing by myself, I would just like some hint that will make me understand in which directions the algorithm should go.
I hope you mean IDs, not passwords. You must never tell a user that their password is already in the database! That means they now just have to try all other user names (which might be easy to guess! Anyway, easier to guess than a password) with the password they've tried to set for themselves.
By the way, I'm assuming this is a learning experience, not a production system. In anything that actually handles user logins, you do not ever store passwords, but salted hashes of passwords. That way, someone that gets your database file still can't authenticate with that – because your system doesn't accept hashes, it accepts passwords and calculates the hashes and checks them against the database.
(If this was a production system, you'd also gladly use a well-tested library to manage your data, because then you don't have to worry about your own bugs, or making sure two concurrent processes don't try to write to the file the same time and corrupt it. It might sound a bit like overkill, but sqlite would be such a system where you can trivially make a compact, safe-to-use system and use the built-in hashing functions to store and check password hashes. It's really ubiquitous!)
You can't solve this using
seek
/lseek
, because your text file has variable line length – before reading a line completely, you can't know where the next line starts.So, use higher-level functions to read tab-separated strings.
The way forward here is to
scanf
each line, to get ID, USERNAME and PASSWORD, ignore the password, and check against what the user entered.