Search code examples
cioposix

Do something like fgetc()


The code below works (somewhat). I want it to read a single character from a file and return that character, which it does but the problem is that it reads the same character over and over. When I call it for the second time I want it to remember the last character and read the next one in the file instead.

I'm new to coding. Please any help would be appreciated.

#include "./libft/libft.h"
#include <stdio.h>
# define LINE 20


char getc_fd(int fd)
{
    int     ret;
    char    c;
    if ((ret = read(fd, &c, 1) != 0))
        ;
    return (c);
}

int main(void)
{
    int     fd;
    char    buf[LINE + 1];

    fd = open("./file.txt", O_RDONLY);
    if (fd  == -1)
        return (-1);
    buf[0] = getc_fd(fd);
    /*buf[LINE] = 0;*/
    printf("%s", buf);
    return (0);
}

Solution

  • Oups. Each time you open a file for reading, the file pointer is positionned at the beginning of the file. And you cannot pass an opened file through different invocations of a program.

    I think that is is time to learn for loop in your main:

    int main(void)
    {
        int     fd;
        char    buf[LINE + 1];
    
        fd = open("./file.txt", O_RDONLY);
        if (fd  == -1)
            return (-1);
        for (int i=0; i<LINE; i+++) {
            buf[i] = getc_fd(fd);
        }
        buf[LINE] = 0;
        printf("%s", buf);
        return (0);
    }
    

    Next lesson should be: how can getc_fd report an error or end of file condition to its caller? (hint: look at getc definition)