On Fri, Jun 26, 2015 at 10:56 AM, Tudor Girba <tudor@tudorgirba.com> wrote:
Hi,

How would you replace a piece of text in a file with another one and persist the change on disk?

Right now, I have:

file := 'path' asFileReference
contents := file readStreamDo: #contents.
newContents := contents copyReplaceAll: 'PATTERN' with: 'TARGET'.��

why not just
newContents := file contents copyReplaceAll: ...


and since we already have contents
why not also add
~~~~~~~~~~~~~~~~
AbstractFileReference>>contents: aCollection
�� �� self writeStreamDo: [ :stream |
�� �� �� �� stream
�� �� �� �� �� �� resetContents;
�� �� �� �� �� �� nextPutAll: aCollection
�� �� ]
~~~~~~~~~~~~~~~~

And then you could do

~~~~~~~~~~~~~~~~~~~~~~~
file := 'path' asFileReference
newContents := file contents copyReplaceAll: 'PATTERN' with: 'TARGET'.��
file
ensureDelete;��
�� �� �� �� contents: newContents
~~~~~~~~~~~~~~~~~~~~~~~

However personally I really don't like the "ensureDelete" (or FileStream forceNewFileNamed: aFileName do: [ :stream | ... ],
and I got burned by it couple of times when I forgot about it... easy way to corrupt your files.

I mean, what is the use-case of overriding just the beginning?��In most languages the default is write (override whole file) and append (add at the end)... and if you need fine control then you fseek().

This is maybe so each write to the stream doesn't reset it? What about clearing just on the first write to the stream?

Peter