Thread: File copying using get() and seekg()

  1. #1
    Registered User
    Join Date
    Jan 2006
    Posts
    2

    Question File copying using get() and seekg()

    I am trying to complete this lab for my course and I'm having some trouble with newly-learned functions get() and seekg(). Even before completeing all the specifications of the assignment, I'm just trying to output the contents of text.txt onto the screen using get(), and then find out where the "internal cursor" is using seekg().

    Here is my test.txt:
    Code:
    Hey there how are you doing?
    Here is Untitled3.cpp:
    Code:
    // read a file into memory
    #include <iostream>
    #include <fstream>
    using namespace std;
    
    int main () {
      int length;
      
      ifstream is;
      is.open ("test.txt", ios::in | ios::binary );
    
      char ch;
      while(!is.eof()) {
        length = is.tellg();
        is.get(ch);
        cout.put(ch);
      }
    
      cout << length << endl;
      
      is.seekg(0);
      length = is.tellg();
      cout << length << endl;  
    }
    Here's the output:
    Code:
    Hey there how are you doing?
    
    30
    -1
    Now it looks to me like the command "is.seekg(0);" has returned made some sort of error, or else tellg() wouldn't return -1, am I right? Technically, I didn't move the internal cursor at all, so why does its position jump from 30 to -1 like that? It's really bugging me . The code functions with the same glitch if I replaced "is.seekg(0);" with "is.seekg(ios::beg);".

    I'm running Bloodshed Dev-C++ 4.9.9.2 on XP SP2. Thank you for any guidance you can give this young coder.

  2. #2
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    You are reading the complete file until you hit eof. this is actually some kind of error state for the stream. so after hitting eof the getpointer is not moved anymore by your
    Code:
    is.seekg(0);
    Just call is.clear() before that.
    Kurt

  3. #3
    Registered User
    Join Date
    Jan 2006
    Posts
    2
    I've inserted your correction and now it works! I didn't realize that eof is an error state for seekg(), thank you for enlightening me.

Popular pages Recent additions subscribe to a feed