-2

How read function know the next position to read from a file. or How can I manage to made a function that can remember last offset of file even after open another file a changing it's file descriptor. Is there is a way to know that a file descriptor is already opened and pointed to a file?

like this:

int main()
{
  int fd;
  char *file;

  file = (char *)malloc(sizeof(char) * 32);
  fd = open("file.txt", O_RDONLY);
  read_file(fd, *file); /* reading the first line from file.txt */

  fd = open("file1.txt", O_RDONLY);
  read_file(fd, *file); /* reading the first line from file1.txt */

  fd = open("file.txt", O_RDONLY);
  read_file(fd, *file); /* Now it should read the second line from file file.txt, how can I manage to do that*/

  close(fd);
  return (0);
}
f0rkr
  • 13
  • 2

2 Answers2

2

The current location in the file is maintained by the kernel I think, the file descriptor serves as the key to all the information associated with the open file.

If you need to open and read from two files at the same time, they should of course not share the file descriptor. Just use two, one per file.

const int fd1 = open("file.txt", O_RDONLY);
const int fd2 = open("file1.txt", O_RDONLY);

The treatment of char *file in your code makes no sense, but at this point you can mix accesses to fd1 and fd2.

Remember to close the files when you're done:

close(fd2);
close(fd1);

In real code you would also check that the open-calls succeeded, before trying to do I/O from the file(s), of course.

unwind
  • 391,730
  • 64
  • 469
  • 606
  • Thanks in advance for your answer !! but my question was how can remember the last offset of file so we can continue to reading where we left. – f0rkr Oct 15 '19 at 09:20
  • This is beginning to sound like [an XY problem](https://en.wikipedia.org/wiki/XY_problem); what you're asking makes little sense since there is a better way of doing it. – unwind Oct 15 '19 at 09:52
0

Is there a way to know that a file descriptor is already opened and pointed to a file?

If you can lseek(fd, 0, SEEK_CUR) successfully, that means that fd is opened and seekable (so probably a file, but remember that "file" includes directories and device files as well as regular files).

If it returns (off_t)-1 and errno==EBADF then the descriptor is not open; if returns (off_t)-1 and errno==ESPIPE, then it's a pipe, socket, or FIFO.

Toby Speight
  • 27,591
  • 48
  • 66
  • 103