0

I am writing a routine to check if a username has already been registered on an internal database. In particular the following function "should" return the length of only one single line of the database:

int line_bytes(int database, off_t line){
    int c, len;
    lseek(database, line, SEEK_CUR);
    for(len = 0; read(database, &c, 1) == 1; len++)
        if(c == '\n');
            return len;
}

Though, it returns the whole file length (all the chars on the file). So the question: is the problem read()? The low-input function read all the file in one single cycle and return the whole file length?

To help, the database format is:

username \t password\n
...\n
...\n
last-username \t last-passwotd\n
8
  • 3
    You are reading 1 byte into int, and then checking the whole (4-byte?) int. Did you mean char c? Mar 14, 2022 at 9:16
  • It's unclear whther the edit to remove the offending ; was to correct a typo, or to fix the error. It's thrown the code posted into doubt. Always copy/paste the exact code. Mar 14, 2022 at 9:22
  • Thanks. This was the problem. Just to be clear: the way I was doing is wrong because, reading 1 byte of char into a 4 byte int, left memory not initialized (hence garbage) on so the char '\n' was never found?
    – user14158054
    Mar 14, 2022 at 9:22
  • 2
    Just FYI, reading one char at a time is extremely slow. System calls are very expensive (especially on modern x86-64 Linux with Spectre and Meltdown mitigation), tens of thousands of times slower then the amortized per-char cost of memchr(buf, '\n', read_len) to search in chunks of up to 8kiB for example, depending on how much data is in the rest of the file. (32kiB would be even more efficient for bulk I/O, but most lines are much shorter than that so if you only want a single line at a given seek position, 4k or 8k is very likely to get it. But not guaranteed, so it needs more code.) Mar 14, 2022 at 10:54
  • 2
    Hints to make your life easier: Build with -Wall -Wextra -Werror. Always use {} even when not required. Always check and print/log errors of any IO (except stdout/stderr output) functions (here lseek and read).
    – hyde
    Mar 14, 2022 at 11:39

1 Answer 1

0

You have a ; on the if-statement. Remove it. ;) Also add a return after the loop, like return -1;

Your code does erroneously:

int line_bytes(int database, off_t line) {
    char c; int len;
    lseek(database, line, SEEK_CUR);
    for (len = 0; read(database, &c, 1) == 1; len++)
        if (c == '\n') {
            ;
        }
    }
    return len;
}

Better char c as when 1 byte is read the other bytes of the int are uninitialized, and on a big-endian the char is misplaced.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.