You can use
getpwent to get all of the uid's from /etc/passwd then find a free one, or alternately you could run through uid's with
getpwuid until you find a free one. Both of these suffer from the fact that a free uid is not necessarily free once you have found it (since another process could have added it right after you found it was free). I assume that programs like useradd will lock the /etc/passwd to prevent this situation, but they may use
fcntl for file locking as it is more portable than
flock (you can build perl to emulate
flock with fcntl(2), but by default it will use flock(2) if available). For groups it would be the same, with
getgrent and
getgrgid.