1

I want to use fgets twice on the same stream. I have defined two file pointer pointing to the same file but when I use fgets on one of the pointer, the other also gets modified.

fun(FILE * input) {
    FILE * input_dup=input;
    char str[2];
    fgets(str, 2, input);
    fgets(str, 2, input_dup);
} 

On the second call to fgets, why is it reading the next character.. It should give the same output as they both are pointing to the same location

Inam
  • 11
  • 3

2 Answers2

2

Well, you are laboring under a fundamental mis-understanding:

If you copy a pointer, that does not copy the object it points to.

As it happens, there's no standard way for duplicating a FILE (though there are nonstandard ones, see: Duplicating file pointers?).
Which doesn't happen you are SOL, you can just use ftell to get the current position, and fseek to get back there (provided the stream is seekable, like a file).

Community
  • 1
  • 1
Deduplicator
  • 44,692
  • 7
  • 66
  • 118
  • I'm simply assuming that you are actually handling `FILE*` and forgot the return-type `void`, or the question wouldn't make any sense. – Deduplicator Oct 20 '15 at 19:18
  • Yes, but if you increment a copied pointer, the original doesn't increment. The misunderstanding likely stems from a belief that a "file pointer" is actually itself a pointer into the file, which marches through the file as data is read. :) – Kaz Oct 20 '15 at 19:59
  • @deduplicator : thanks ☺.. even I have achieved, it using ftell and fseek. But I wanted to know what I am doing wrong in the above code. – Inam Oct 21 '15 at 02:37
-1

As with all C++ coding, it is doing exactly what you told it to do. If you want another copy, you could make an overriding function that tells the system to read and act and copy the stream and return a pointer to an array. That would accomplish your goal.

Asecond solution would be to unget the stream's last char, then read again.