'Reading-File Algorithm keeps repeating data of previous lines

I am trying to write an algorithm able to read through a file searching a specific string, which in my case is called 'label'. The concept is simple: Read each line until EOF and for each line process the content searching for a specific sequence of characters.

The function:

char *fsearch(int fd, char *label){
    char c, buffer[500];
    int len, end, k;

    if((fd = open("C:\\Password-Manager\\pssw.txt", O_RDONLY, 0)) == -1){
        fprintf(stderr, "Unable to locate file.");
        return NULL;
    }
    for(len = 0; read(fd, &c, 1) == 1;){
        if(c == '\n')
            len++;
    }
    printf("[DEBUG]: File-Length -> %d\n", len);

    lseek(fd, 0, SEEK_SET);
    end = k = 0;
    while(len > 0){
        while(read(fd, &c, 1) == 1){
            if(c == '\n')
                break;
            buffer[k++] = c;
        }
        printf("[DEBUG]: %s\n", buffer);
        len--;
    }
}

The function is not completed yet, next step will be parsing the content, but the problem happens right here. With a printf() are shown on screen the line that have been save and which will be look up late, here is the result:

C:\Users\Computer\Desktop\Not_Compressed_Folder\Password Managment System\1.0h>init -sh
[DEBUG]: File-Length -> 3
[DEBUG]: label0 string0
[DEBUG]: label0 string0label1   string1ª↕
[DEBUG]: label0 string0label1   string1label2   string2

Why is each time starting over? I supposed was something about the cursor, that jump back to the beginning each time the first while starts over. I still don't know how to fix it. Any kind of help will be gladly appreciated. Thanks for your time.



Solution 1:[1]

It's just because you never delete the content of the buffer, and you keep incrementing k. So one way to fix this is to put '\0' when you finish reading a line and then you set k back to 0:

while(len > 0){
    while(read(fd, &c, 1) == 1){
        if(c == '\n')
            buffer[k] = '\0';
            break;
        buffer[k++] = c;
    }
    printf("[DEBUG]: %s\n", buffer);
    k = 0;
    len--;
}

I haven't tried this since I don't have the full code, let me know if it doesn't work.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Claudio