Reputation:
I have some questions on manipulating on a file ;
a.) I am a bit confused about get and put pointer in c++. Do I show correct position of get pointer and put pointer.
MyFile . seekg ( 0 , ios :: beg ) ;
MyFile . seekp ( -10 , ios :: end ) ;
index :0 1 2 3 4 5 6 7 8 9 10 ... -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0
__________________________________________________________________
^ ^
^ ^
^ ^
get Pointer put pointer
Myfile . get ( character ) ;
MyFile . write ( SomeString, 4 ) ;
MyFile . flush ( ) ;
index :0 1 2 3 4 5 6 7 8 9 10 ... -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0
__________________________________________________________________
^ ^
^ ^
^ ^
get Pointer put pointer
i.) Are Seekg and seekp always guarentee that get an put pointer always shows correct position ?
ii.) If you know more about this topic, can you show/give me some point(s) I should be careful when I use them, ( if there is )
b.) Is
FileIN . seekg ( 1, ifstream :: cur ) ;
equal to
FileIN . seekg ( 1, ios :: cur ) ;
Platform : linux File format : binary
Upvotes: 4
Views: 3951
Reputation: 72519
a) It's wrong. File streams maintain one file pointer, for both input and output. Both seekg
and seekp
do the same thing. The reason there are two different functions is that the interface of iostreams is generic, it can be used for devices which do have separate put and get pointers.
Quote from the standard [filebuf]:
In particular:
— If the file is not open for reading the input sequence cannot be read.
— If the file is not open for writing the output sequence cannot be written.
— A joint file position is maintained for both the input sequence and the output sequence.
b) Yes, they are the same.
EDIT:
index :0 1 2 3 4 5 6 7 8 9 10 ... -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0
_____________________________________________________________________
^ file-pointer
MyFile . seekg ( 0 , ios :: beg ) ;
index :0 1 2 3 4 5 6 7 8 9 10 ... -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0
_____________________________________________________________________
^ file-pointer
MyFile . seekp ( -10 , ios :: end ) ;
index :0 1 2 3 4 5 6 7 8 9 10 ... -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0
_____________________________________________________________________
^ file-pointer
Myfile . get ( character ) ;
// you must sync/flush if your last operation was input and you switch to output,
// or your last operation was output and you switch to input.
MyFile . sync ( ) ;
index :0 1 2 3 4 5 6 7 8 9 10 ... -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0
_____________________________________________________________________
^ file-pointer
MyFile . write ( SomeString, 4 ) ;
MyFile . flush ( ) ;
index :0 1 2 3 4 5 6 7 8 9 10 ... -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0
_____________________________________________________________________
^ file-pointer
Upvotes: 4