going back to beginning of file

This is a discussion on going back to beginning of file within the C++ Programming forums, part of the General Programming Boards category; Hi everyone, I am reading a binary file completely, but I would like to restart reading the file, by moving ...

  1. #1
    Registered User
    Join Date
    Jul 2008
    Posts
    52

    going back to beginning of file

    Hi everyone,

    I am reading a binary file completely, but I would like to restart reading the file, by moving to the beginning of the file again. I have tried using file.seekg(0, ios::beg); but it doesn't seem to work.

    In a readfile function I read the file once, and it works.

    Code:
        vector<uint32_t> buf(numcols);
    
        if(file.is_open())
        {
            while (file.read(reinterpret_cast<char*>(&buf[0]), sizeof(uint32_t)*numcols))
            {
                for(size_t i = 0; i < numcols; ++i)
                {
                    freq[i][buf[i]]++;
                }
            }
        } 
    
        file.seekg(0, ios::beg);    // This supposedly brings the pointer to the beginning  of the file again.
    in another function I try:

    Code:
     while (file.read(reinterpret_cast<char*>(&buf[0]), sizeof(uint32_t)*numcols))
            {
                for(size_t i = 0; i < numcols; ++i)
                {
                    freq[i][buf[i]]++;
                }
            }
    but strange numbers indicate that it isn't actually reading the file from the beginning.

    Ted.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,845
    You also need file.clear() to reset the EOF state, if you ran into the end of file.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    Registered User
    Join Date
    Jul 2008
    Posts
    52
    Thanks that worked.

    Ted.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Memory Leak in AppWizard-Generated Code
    By jrohde in forum Windows Programming
    Replies: 4
    Last Post: 05-19-2010, 05:24 PM
  2. Formatting the contents of a text file
    By dagorsul in forum C++ Programming
    Replies: 2
    Last Post: 04-29-2008, 01:36 PM
  3. Can we have vector of vector?
    By ketu1 in forum C++ Programming
    Replies: 24
    Last Post: 01-03-2008, 05:02 AM
  4. Encryption program
    By zeiffelz in forum C Programming
    Replies: 1
    Last Post: 06-15-2005, 04:39 AM
  5. Need a suggestion on a school project..
    By Screwz Luse in forum C Programming
    Replies: 5
    Last Post: 11-27-2001, 02:58 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21