1

Friend, How can open a txt file in Squeak4.1 ,the code Shall be like this:

at: #f put: (FileStream  open: '/root/test'  mode: FileStream read) !
f do: [ :c | Transcript nextPut: c ] !
f close !

can any body give some hints on how to open the file and do the + - * / equation ? thanks first :)

parsifal
  • 879
  • 4
  • 12
  • 21

3 Answers3

1

This should work:

|file fileContents|
file := FileStream fileNamed: '/root/test'.
fileContents := file contentsOfEntireFile.
file close.
Bernat Romagosa
  • 1,172
  • 9
  • 15
1

I'd use one of these methods...

fileContents := FileStream 
                   readOnlyFileNamed: '/root/test' 
                   do: [:f | f contents ].

Using the block form above automatically closes the file, you can't forget. Or..

fileContents := (FileStream readOnlyFileNamed: '/root/test') 
                    contentsOfEntireFile.

#contentsOfEntireFile also automatically closes the file, you don't need to do it again.

In a language with blocks, it just makes no sense to manually close the stream when higher order methods are available that ensure you don't have to do so.

Ramon Leon
  • 547
  • 2
  • 5
  • Thanks friend, it works! As a plus, ^fileContents will make the code work well, Suppose entering "(MyInteger new) ReadFrom" into Workspace ,and print it, then it will return the content in your specified file from readOnlyFileNamed to Workspace. – parsifal Feb 16 '11 at 04:59
1
|f|
f:=StandardFileStream fileNamed: 'myFile.txt'.
Transcript show: f upToEnd.
f close.

I use StandardFileStream for raw input without UTF-8 detection and read upToEnd because reading single characters is not considered apropriate.

Bernd Elkemann
  • 23,242
  • 4
  • 37
  • 66
  • friend, the answer you supply answer the absolute directory of `myFile.txt` not the content What the program want to behave, still thanks :) – parsifal Feb 16 '11 at 05:27
  • Hi @parsifal. Whether you place an absolute or relative path in the quotes is up to you. Also, this version will work in older Squeaks and other Smalltalks (with FileStream instead of StandardFileStream) as well. – Bernd Elkemann Feb 16 '11 at 07:01