[Tutor] Simultaneous read and write on file

Cameron Simpson cs at zip.com.au
Mon Jan 18 22:55:47 EST 2016


On 18Jan2016 21:07, ALAN GAULD <alan.gauld at btinternet.com> wrote:
>On 18/01/16 20:43, Cameron Simpson wrote:
>>> The + modes are deceptively appealing but they are full of dangers
>>> for precisely the reasons you have discovered(*). You very rarely
>>> need them and you are better opening/closing the file and
>>> using explicit modes to read/write.
>>
>> But if he wants to mix the modes, he certainly should be experimenting. Having
>> a file open for read and write is sometimes useful; I do it myself in certain
>> circumstances.
>
>Yes and so have I. Maybe twice in 30 years of programming.
>It's sometimes necessary but it's much, much harder to get
>right and very easy to get wrong, usually with data corruption
>as a result.

I may have done it a little more than that; I agree it is very rare. I may be 
biased because I was debugging exactly this last week. (Which itself is an 
argument against mixed rerad/write with one file - it was all my own code and I 
spent over a day chasing this because I was looking in the wrong spot).

>So for a beginner I would never encourage it. For an
>experienced programmer sure' if there is no other option
>(and especially if you have fixed size records where
>things get easier).
>
>> Tip for new players: if you do any .write()s, remember to do a .flush() before
>> doing a seek or a read
>
>That's exactly my point. There are so many things you have
>to do extra when working in mixed mode. Too easy to treat
>things like normal mode files and get it wrong. Experts
>can do it and make it work, but mostly it's just not needed.

Yes. You're write - for simplicity and reliability two distinct open file 
instances are much easier.

>> Disagree. As far as his question goes, "wb+" is a correct mode for what he is
>> trying. Whether it is a sensible approach depends very much on what he is doing
>> with his files.
>
>I'm not sure we know what he(?) is trying.
>We only know he successfully overwrote his data and
>that apparently was not his intention. There are use
>cases where it makes sense but in most cases you can
>get by just fine without.

Yeah. I think I was more narked by your not answering his "is wb+ correct" 
literally; it may be only rarely the reasonable course, but for what he was 
actually _asking_ wb+ is correct. He may not be doing the best design but as 
you say we don't know his actual use case.

For the narkiness I apologise.

Cheers,
Cameron Simpson <cs at zip.com.au>


More information about the Tutor mailing list