Why I get a wrong file size with tellg?

Dec 14, 2019 at 11:10pm
Why do I get a file size of 2?
As input file, I take my source file.

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
/* streamtest.cpp
 */
#include <fstream>
#include <iostream>


int main()
{
    std::streampos size, begin, end;
    
    std::fstream file( "streamtest.cpp", 
        std::ios::in | std::ios::binary
    );
    if (!file ) std::cerr << "streamtest.cpp couldn't opened.";
    
    file.seekg( std::ios::beg);
    begin = file.tellg();
    
    file.seekg( std::ios::end);
    end = file.tellg();
    
    size = end - begin;
    char * buf = new char[size];
    file.read( buf, size);
    
    file.close();
    
    std::cout << "begin:"<<begin<<" end:"<<end<<" end-begin:"<<size<<'\n';
    
    file.open( "streamtest.out.cpp",
        std::ios::out | std::ios::binary
    );
    file.write( buf, size);
    
    delete buf;
}
begin:0 end:2 end-begin:2


Last edited on Dec 14, 2019 at 11:13pm
Dec 14, 2019 at 11:23pm
You are using seekg incorrectly. You are using the values of the constants ios::beg and ios::end as the offsets! Presumably their values are 0 for beg and 2 for end. Hence your result.
https://en.cppreference.com/w/cpp/io/basic_istream/seekg
Dec 14, 2019 at 11:36pm
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
// streamtest.cpp
#include <fstream>
#include <iostream>

int main()
{    
    std::fstream file( "streamtest.cpp", file.in | file.binary);
    if (!file ) {
        std::cerr << "streamtest.cpp couldn't opened.";
        return 1;
    }

    file.seekg(0, file.end);  // you only need the end position to determine the size
    auto size = file.tellg();
    std::cout << "size: " << size << '\n';

    // you need to seek back to the start before the read
    file.seekg(0, file.beg);

    auto buf = new char[size];
    file.read( buf, size);
    file.close();
    
    file.open( "streamtest.out.cpp", file.out | file.binary);
    file.write( buf, size);
    delete buf;
}

Last edited on Dec 14, 2019 at 11:37pm
Dec 14, 2019 at 11:53pm
Thank you dutch!
Topic archived. No new replies allowed.