0

Usually lseek doesn't work on stdin.

But, what if I run my program like this:

./a.out < filename

Now stdin is a file and not keyboard.

Will lseek work there?

Can I do

lseek(0, -1, SEEK_CUR)

and get the same effect like

ungetc() ?

Alex
  • 9,891
  • 11
  • 53
  • 87
Sam
  • 1,842
  • 3
  • 19
  • 33

1 Answers1

1

Yes, lseek will change the seek pointer. No, it is not equivalent to ungetc().

fseek(stdin, -1, SEEK_CUR) comes closer to ungetc(), but still isn't identical.

Robᵩ
  • 163,533
  • 20
  • 239
  • 308
  • Can I get the effect of `ungetc` using `lseek`? – Sam Mar 17 '13 at 10:16
  • Not generally. What effect of `ungetc` are you seeking? – Robᵩ Mar 17 '13 at 10:17
  • I am parsing text... I am writing a function like gettoken() from a file. But I am doing < or dup2 and redirecting the file to stdin I am reading token characters and when token is parsed, the last character(one after the token) needs to be pushed back... Is there any system call equivalent to ungetc? because ungetc takes a FILE* arg and I am working on file descriptors... – Sam Mar 17 '13 at 10:23
  • 1
    If you are `read()`ing the characters from a file descriptor, then yes, `lseek(-1)` has a similar effect with respect to a file descriptor as `ungetc` has with respect to a `FILE*`. – Robᵩ Mar 17 '13 at 10:27
  • No I am `getchar`ing it and that's why I am not getting the effect I think write? – Sam Mar 17 '13 at 10:31
  • 1
    To undo a `ch = getchar()`, you must call `ungetc(ch, stdin)`. You have contradicted yourself: "I am working on file descriptors" is opposite to "I am `getchar`ing it". – Robᵩ Mar 17 '13 at 10:33
  • Oh man... I was doing `ungetc(ch, 0)` and getting segmentation fault! You solved my problem bro!!! `ungetc(ch, stdin)` works like a charm... Thanks !!!!!!!!! – Sam Mar 17 '13 at 10:38