46

Is there a way to do what ftell() does (return the current position in the file) on a raw file descriptor instead of a FILE*? I think there ought to be, since you can seek on a raw file descriptor using lseek().

I know I could use fdopen() to create a FILE* corresponding to the file descriptor, but I'd rather not do that.

HighCommander4
  • 50,428
  • 24
  • 122
  • 194

1 Answers1

87

Just use:

position = lseek(fd, 0, SEEK_CUR);
Community
  • 1
  • 1
Darron
  • 21,309
  • 5
  • 49
  • 53
  • 1
    For file length, `lseek(fd, 0, SEEK_END);` – SF. Feb 05 '19 at 15:14
  • @SF.By the way, would it be better to use `fstat` or `lseek` for the size of a file? – Yi Lin Liu Feb 21 '19 at 15:04
  • @SF. note that this will also move the file descriptor to the end of the file if it is not located there yet, which is not necessarily what you want. – sagivd May 02 '19 at 17:51
  • 6
    @YiLinLiu: It seems that fstat gathers a lot more info about the file than just size. Use stat if you want just to learn about a file but don't open it; lseek if you open the file and need just the size, fstat if you open the file and need more than just the size. – SF. May 02 '19 at 23:58