Reading File twice in a Program

Can anyone tell me how to read file twice in a single program?
There's no magic to it. If you need to read a file twice, then just do the same the second time as you did the first time.
As mikeyboy said, except if you want to read it twice without closing it you can call fseek() to move the read pointer back to the start of the file.
Another possible alternative is to read the file into memory all at once and use it from there. This can be done with anyone of the standard dynamic containers: http://www.cplusplus.com/reference/stl/

I should note that this is impractical for very large files. Anything over I'd say a Gig may be better off with a different approach depending on the system that it is being run on.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <iostream>
#include <fstream>
#include <string>

int main()
{
    // read the same file twice: use two different stream objects
    {
        {
            std::ifstream file( __FILE__ ) ;
            int n = 0 ;
            char c ;
            while( file >> c ) ++n ;
            std::cout << n << " non-whitespace characters\n" ;

            // the life-time of the stream object is over; it is destroyed when the block is exited
        }

        {
            std::ifstream file( __FILE__ ) ; // create another stream object
            int n = 0 ;
            std::string str ;
            while( std::getline( file, str ) ) ++n ;
            std::cout << n << " lines\n" ;
        }
    }

    // read the same file twice: re-open the file
    {
        std::ifstream file( __FILE__ ) ;
        int nc = 0 ;
        char c ;
        while( file >> c ) ++nc ;
        std::cout << nc << " non-whitespace characters\n" ;

        // note: re-opening the file clears the failed state
        file.close() ;
        file.open( __FILE__ ) ;

        int ns = 0 ;
        std::string str ;
        while( std::getline( file, str ) ) ++ns ;
        std::cout << ns << " lines\n" ;
    }

    // read the same file twice: clear the failed state, seek to the beginning
    {
        std::ifstream file( __FILE__ ) ;
        int nc = 0 ;
        char c ;
        while( file >> c ) ++nc ;
        std::cout << nc << " non-whitespace characters\n" ;

        file.clear() ; // clear the failed state of the stream
        file.seekg(0) ; // seek to the first character in the file

        int ns = 0 ;
        std::string str ;
        while( std::getline( file, str ) ) ++ns ;
        std::cout << ns << " lines\n" ;
    }
}

http://coliru.stacked-crooked.com/a/e1b1cdaaa681fd34
Topic archived. No new replies allowed.