0

I would like to know if there is an equivalent of fseek and ftell when I'm working in main.

For example, if I type the name of a file when asked, at end I hit enter. Next I'll ask the user another file name, but there's a '\n' in the buffer that was not read. The user won't be able to type the name of the second file because the program will read the '\n'. So I would like to move one position forward in the buffer. Normally in a file I would do:

fseek(file, ftell + 1, SEEK_SET);

I would like to do the same thing when I'm in main, not working with a file.

Filburt
  • 17,626
  • 12
  • 64
  • 115
Thi G.
  • 1,578
  • 5
  • 16
  • 27
  • Do you mean reading inputs from console/`stdin`? If that is the case then you need to *flush* input stream. Please see [this post](http://stackoverflow.com/questions/2187474/i-am-not-able-to-flush-stdin) for pointers – another.anon.coward Jun 09 '13 at 15:40
  • You *are* working with a file. The file you're working with just happens to be `stdin`. For example, `getc(stdin)` and getchar()` are exactly equivalent; `stdin` can be thought of as an implicit parameter. – Keith Thompson Aug 29 '13 at 23:23
  • *How* exactly are you reading this file name? If you use `fgets()`, ti will consume the `\n`. If you use `scanf("%s", ...)`, it won't, but you can't avoid overflowing the array in which you store the name. Show us a [small complete program](http://sscce.org/), and we can help you get it working. As it stands, you're *assuming* that `fseek` is the right solution. You almost certainly have an [XY problem](http://meta.stackexchange.com/q/66377/167210). – Keith Thompson Aug 29 '13 at 23:25

2 Answers2

1

The easiest way to do this would be just to say

getc(stdin);

or even shorter

getchar();

and ignore the returned character.

cmaster - reinstate monica
  • 38,891
  • 9
  • 62
  • 106
1

Actually, it is possible to use fseek in main, you just have to set FILE * stream to stdin, so it would be:

fseek(stdin, ftell - 1, SEEK_SET);
Thi G.
  • 1,578
  • 5
  • 16
  • 27
  • Your question (and answer) don't make sense. Of course you can call `fseek` within `main`. Why wouldn't you be able to? You're asking about calling `fseek` and `ftell` on things like `stdin` (which have nothing to do with `main`). That said, it doesn't make much sense to call `fseek` on `stdin`. Also see: http://stackoverflow.com/questions/4917801/using-fseek-with-a-file-pointer-that-points-to-stdin – jamesdlin Aug 29 '13 at 23:30
  • I knew you had to specify a file to use `fseek`, I just didn't know the file I wanted was `stdin`, that reads the input from the console. – Thi G. Aug 29 '13 at 23:32