C++ IO: Unable to Get Random Access to Text Files

Tom Browder tom.browder@gmail.com
Mon Aug 25 20:50:00 GMT 2008


This is a two-part question, and all is moot if it is not possible to
do random access on a text file.

Part 1.
=====

I would like to be able to check the first few characters of a text
file, and then check the last few characters of a text file to
determine the type of file it is without having to do a line-by-line
check (it's an XML file).  I have been unable to get seekp or seekg to
work.  Here's a sample of what I've been trying:

string hdr; // varies depending on data

const string ender1("</root>\n")
const string ender2("</root><!-- incomplete -->\n")

fstream f; // will be used for in and out

f.open("f.xml", ios::in);
char c;
string buf;
for (unsigned i = 0; !f.eof() && i < hdr.size(); ++i) {
  f.get(c);
  buf += c;
}
if (buf != hdr)
  ; // do something

buf.clear()
f.seekg(ios::end - ender1.size());
for (unsigned i = 0; !f.eof() && i < ender1.size(); ++i) {
  f.get(c);
  buf += c;
}
if (buf != ender1)
  ; // do something
// etc.

The first part, the hdr check works fine, but the seek and subsequent
reads don't.  I get one character, a newline, regardless of how much i
back up from the end.

What am I doing wrong?  Do I need to specify the ios:;binary mode?  Is
random seeking of text possible?

I have tried the readsome function instead of the get function but I
can't get it to work either.  I have tried the relative form of seekg
with

  streampos relpos = -1 * ender1.size()l
  f.seekp(relpos, ios::end);

Still no success.

Part 2:
=====

If I could get part 1 to work, then I would like to do this:

f.close();
f.seep(ios::end - ender2.size());
f << data;
...
f << ender1;
f.close();

Essentially these two parts are so I can have a restart capability if
my xml-writing process is interrupted.  I will leave the unfinished
xml in a well-formed state, but then I can pick up where I left
without rewriting or copying the file just to add data.

Any ideas or suggestions are very welcome.

Thanks so much.

-Tom

I



More information about the Gcc-help mailing list