seekp and seekg move the same pointer

95 views
Skip to first unread message

antonio

unread,
Aug 14, 2009, 6:33:59 PM8/14/09
to PPP-public
In 11.3.3 you say that every file open for reading has a "read/get
position" and every file open for writing has a "write/put position".
I think that in file streams (open for read and write) both pointers
are the same, (I made a simple example showing that) or, at least,
both move jointly, and only in stringstreams are diferent.
Maybe there is a reason to not explain that, but I think can be a
source of misunderstandings.
Thanks for this definitive book.
Antonio.

dtopham

unread,
Aug 14, 2009, 7:24:27 PM8/14/09
to PPP-public
Antonio, Would you be willing to share that example? I believe that
those two pointers are independent when file is opened for reading and
writing. The idea is to able to read from one part of file, while
writing to another. -Dave

antonio

unread,
Aug 14, 2009, 7:44:27 PM8/14/09
to PPP-public
Ok Dave. Here is the code.
Thanks.
/*
I am trying to demostrate that:
In a fstream, seekp and seekg move at same time
In a stringstream, seekp and seekg move independent
Antonio Vazquez Araujo
*/

#include <iostream>
#include <cstdlib>
#include <iomanip>
#include <fstream>
#include <sstream>
using namespace std;
char cad[10]={"xxx"};
void status(const char * comando);
fstream f("datos", ios::in|ios::out|ios::binary|ios::trunc);
stringstream s(stringstream::in|stringstream::out|
stringstream::binary);
int main() {
cout.setf(ios::left);

cout << "First with an fstream"<<endl;
cout << setw(20) << "Command" <<
setw(15) << "f.tellg()" <<
setw(15) << "f.tellp()" <<
setw(15) << "s.tellg()" <<
setw(15) << "s.tellp()" << endl;
cout.setf(ios::right);



if(!f) {
cout << "Error opening file!"<<endl;
exit(-1);
}

f.seekp(0);
status("f.seekp(0)");
f.seekg(0);
status("f.seekg(0)");

f.write(cad, 10);
status("f.write(cad, 10)");

f.seekp(0);
status("f.seekp(0)");

f.read(cad, 10);
status("f.read(cad, 10)");

f.seekp(0);
status("f.seekp(0)");

f.seekp(5, ios::beg);
status("f.seekp(5)");

f.seekg(8, ios::beg);
status("f.seekg(8)");

f.close();
status("f.close()");

if(!s){
cout << "error opening file"<<endl;
exit(-1);
}
cout << "Now with a stringstream"<<endl;
cout << setw(20) << "Command" <<
setw(15) << "f.tellg()" <<
setw(15) << "f.tellp()" <<
setw(15) << "s.tellg()" <<
setw(15) << "s.tellp()" << endl;
cout.setf(ios::right);
s.seekp(0);
status("s.seekp(0)");
s.seekg(0);
status("s.seekg(0)");

s.write(cad, 10);
status("s.write(cad, 10)");

s.read(cad, 10);
status("s.read(cad, 10)");

s.seekp(0);
status("s.seekp(0)");

s.seekp(5);
status("s.seekp(5)");

s.seekg(8, ios::beg);
status("s.seekp(8)");

cout << endl;
cin.get();
}
void status(const char * comando){
cout.width(25); cout << left<< comando;
cout.width(15); cout << f.tellg() ;
cout.width(15); cout << f.tellp() ;
cout.width(15); cout << s.tellg() ;
cout.width(15); cout << s.tellp() ;
cout <<endl;
}
~
~
~
Reply all
Reply to author
Forward
0 new messages