0

I am experiencing that calling read_from_fd more than once causes the data to be empty.

#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

int fd;

void read_from_fd() {
    char data[2];

    read(fd, data, 1);

    data[1] = 0x00;

    printf("data %s\n", data);
}

int main(void) {
    fd = open("test.txt", O_RDWR);

    read_from_fd();
    read_from_fd();
    read_from_fd();
}

So the first read prints data but the second and third one print something empty.

I guess this has to do something with the memory from char. Is this correct? What do I have to do to fix this?

Bodo

2
  • 1
    Could you show the input file? If there is only one character in the file then clearly you will get it only once. If you want it several times you have to reset the seek pointer using lseek Commented Jun 19, 2013 at 6:48
  • @cgledezma this seems to be the problem! Could you create an answer so I can mark it? Commented Jun 19, 2013 at 6:52

2 Answers 2

2

If there is only one character in the input, then it is clear that you will get it only once. This has to do with the seek pointer in the file. When you perform an open with the O_RDWR flag, the seek pointer is placed at the beginning of the file. Then on every call to read it is moved the amount of bytes read. When the seek pointer reaches the end of the file, the call to read will fill your buffer with 0 and return an appropriate value.

If you want to read the same character over and over, you have to reset the seek pointer using function lseek.

Sign up to request clarification or add additional context in comments.

Comments

0

According to opengroup The behavior of multiple concurrent reads on the same pipe, FIFO, or terminal device is unspecified.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.