Thread: tellg() returning -1

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Dec 2007
    Posts
    932

    tellg() returning -1

    tellg() won't return the size of the file, it returns -1.
    What is the reason for it?
    Code:
    #include <string>
    #include <iostream>
    #include <fstream>
    using namespace std;
    
    fstream file;
    
    int main()
    {
        // Creat file
        ofstream outfile("test.txt");
        outfile.close();
    
        string str ;
        file.open("test.txt", fstream::in | fstream::out);
        if (!file.is_open())
        {
            cerr << "Error opening file." << endl;
            return 1;
        }
    
        file << "Hello World." << endl;
        file.seekg (0, ios::beg);
    
        while(!file.eof()) 
        {
            getline(file, str); 
            cout << str << endl; 
        }
    
        file.seekg(0, ios::end);
        int newsize = file.tellg();
        file.seekg(0, ios::beg);
        cout << newsize << endl;
    
        file.close();
    
        return 0;
    }
    Last edited by Ducky; 01-30-2013 at 03:59 AM.
    Using Windows 10 with Code Blocks and MingW.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Returning an integer ... not returning; weird error
    By Imanuel in forum C++ Programming
    Replies: 19
    Last Post: 09-25-2011, 01:30 PM
  2. Replies: 5
    Last Post: 09-06-2011, 02:59 PM
  3. CSV read problem usng tellg()
    By rogster001 in forum C++ Programming
    Replies: 1
    Last Post: 06-02-2011, 06:01 AM
  4. Recursion: base case returning 1, function returning 0
    By yougene in forum C Programming
    Replies: 5
    Last Post: 09-07-2007, 05:38 PM
  5. tellg and seekg
    By Zoalord in forum C++ Programming
    Replies: 1
    Last Post: 01-11-2004, 02:45 PM