Strange behaviour of tellg() function c++ -


i got problem tellg() function std::fstream class. typically should return position of current character in input stream. however, works strange me. below short sample code:

#include <iostream> #include <fstream>  using namespace std;  int main(void) { char c; ifstream czytaj; czytaj.open("test_file.txt");  cout << czytaj.tellg() << endl;     //is 0 should 0 czytaj.peek();                      //is 0 should 0 cout << czytaj.tellg() << endl;     //is 2 should 0    !! czytaj.get(c);                      //is 3 should 3 czytaj.get(c);                      //is 4 should 4 cout << czytaj.tellg() << endl;     //is 6 should 4    !!  int r; cin >> r; return 0; } 

while txt file looks follows:

abcdefghij kturjbkfvd 

after compilation output like:

0 2 6 

first use of tellg() works properly, returns position 0 beginning of file. unfortunatelly, each next use works adds +2 position. result letters 'c' , 'd' extracted stream. both tellg() , peek() supposed not change position, should letters 'a' , 'b', while correct result should be:

0 0 2 

such things happen if use encoding ansi in txt file. when change unicode, works should. if use ansi , additionally binary mode ios::binary, works well. strange fact is, on other computer works fine ansi , without ios::binary. why happen?

edit: forgot mention important fact. if remove sample code lines containing tellg(), extracting correct - letters 'a' , 'b'.

tellg() tells next "get" position in file is. since files in example windows use cr+lf ('\r','\n') newlines have 2 characters newline, c++ (and c) standard requires newline lf '\n' single character, when program reads cr+lf sequence, c runtime counts 1 character, file position next character 2 steps forward.


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -