file handling, last bit repeating twice

i tried reading a file using fstream class object.
the content of the file was : "i like c++ programming" (without the double quotes)
now when i access the file in input mode to print its contents, i'm getting the following output : "i like c++ programmingg" (without the double quotes)
the last g is printed twice
also after running my code when i'm printing file.tellg(), i get -1 whereas i expect the last bit of the file(it's size), i.e. 22
following is the code for my program :
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
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
int main()
{
    char input[100];
    strcpy(input, "i like c++ programming");
    fstream file("ash.bin", ios :: binary | ios :: in | ios :: out |  ios :: trunc);
    if(!file.is_open())
    {
        cout << "error while opening the file";
    }
    else
    {
        for(int i = 0; i < strlen(input); i++)
            file.put(input[i]);
    }
    file.seekg(0);
    char ch;
    while(!file.eof())
    {
        file.get(ch);
        cout << ch;
    }
    cout << file.tellg();
    return 0;
}
Last edited on
This is wrong:
1
2
3
4
5
    while(!file.eof())
    {
        file.get(ch); // *** this may fail (will fail at eof)
        cout << ch; // *** but we would still execute this line
    }



Canonical: while( file.get(ch) ) std::cout << ch ;
1
2
3
4
5
    while(!file.eof())
    {
        file.get(ch);
        cout << ch;
    }

eof is set after you attempt to read.
http://stackoverflow.com/questions/4533063/how-does-ifstreams-eof-work
in addition to correct replies above
also after running my code when i'm printing file.tellg(), i get -1 whereas i expect the last bit of the file(it's size), i.e. 22

Did you look at tellg docs to see what -1 stands for?
http://www.cplusplus.com/reference/istream/istream/tellg "if member fail returns true, the function returns -1."
http://en.cppreference.com/w/cpp/io/basic_istream/tellg "if fail() == true, returns pos_type(-1)"

Since your loop terminated, stream reached the end and raised a flag. Clear it to see read position indicator:
1
2
    file.clear();
    cout << file.tellg();
Last edited on
Topic archived. No new replies allowed.