Probably trivial fstream question

C

continuation.nomad

I feel like this should be really easy but I'm drawing a blank here.
I have an fstream, it was opened with ios_base::in | ios_base::eek:ut. I
want to REPLACE the next character in the stream with something else.
It doesn't matter whether or not the stream advances by one character
as a result of this, but it must not advance by 2 or more
characters.

Isn't there an easy way to do this, or for that matter a way to do it
at all? I've tried tons of combinations of put, ignore, putback,
read, and write and nothing's working.
 
C

continuation.nomad

file << 'c';

That was one of the things I had also tried. And here is what I
experience: The file originally contains the following text:

ABCDE

I execute the following sequence

file.peek(); file.ignore();
file.peek(); file.ignore();

//file.peek() == 'C' now

file << L'K';

//file.peek() still equals 'C'. I want it to equal 'K'

file.ignore();
//Now file.peek() == 'E'. It should equal 'D'
 
C

continuation.nomad

FYI, it's a little odd to use wide character constants with
narrow-character streams.  There are wide character streams (e.g.
wfstream), but fstream is usually just used with single-byte characters.



That threw me for a second. :)

The put operation advances both the "get" and "set" stream pointers.
The peek you do after the write isn't peeking at the character you think
it is.  Switch from L'K' to 'K', run your program, and look in the file
with your favorite text editor.  It should show the K, just where you
expect it.- Hide quoted text -

- Show quoted text -

Sorry, actually I am using a wfstream, my mistake on that.

That being said, problem is that I actually need to use peek in my
code, and I need it to peek at what I think it's supposed to be
peeking at. Basically I'm scanning a text file character by
character. Depending on the character, I may want to replace it with
another character. But I may not. So I have (or want to have anyway)
something like this (pseudocode):

while (!file.is_eof())
{
if (should_replace(c))
file.replace(c);

file.ignore(); //advance to the next character
}

Perhaps there is no real easy way to specify this, and I should just
use a temporary file and then overwrite the original file
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,054
Latest member
LucyCarper

Latest Threads

Top