public inbox for gcc-help@gcc.gnu.org
 help / color / mirror / Atom feed
* C++ IO: Unable to Get Random Access to Text Files
@ 2008-08-25 20:50 Tom Browder
  0 siblings, 0 replies; only message in thread
From: Tom Browder @ 2008-08-25 20:50 UTC (permalink / raw)
  To: gcc-help

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

^ permalink raw reply	[flat|nested] only message in thread

only message in thread, other threads:[~2008-08-25 19:33 UTC | newest]

Thread overview: (only message) (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2008-08-25 20:50 C++ IO: Unable to Get Random Access to Text Files Tom Browder

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).