|
Class: FileStream
Object
|
+--Stream
|
+--PeekableStream
|
+--PositionableStream
|
+--WriteStream
|
+--ReadWriteStream
|
+--ExternalStream
|
+--FileStream
|
+--DirectoryStream
|
+--SoundStream
|
+--StandardFileStream
- Package:
- stx:libbasic
- Category:
- Streams-External
- Version:
- rev:
1.248
date: 2023/11/26 12:35:58
- user: cg
- file: FileStream.st directory: libbasic
- module: stx stc-classLibrary: libbasic
This class provides access to the operating systems underlying file
system (i.e. its an interface to the stdio library).
Notice, that on some systems, the standard I/O library has performance
problems when a file is opened for readwrite.
For best results, open files either readonly or writeonly.
Also notice, that some OperatingSystems do not fully support
positioning a file stream.
For example, poor VMS does not allow positioning onto arbitrary
byte boundaries if the file is a variable-record-RMS file.
(stupid enough, this is the default for textfiles as created by some tools ...)
Therefore, the instance variable canPosition is set according to
this and an error is raised, if a position: is attemted.
I know, this is ugly, but what else could we do ?
Late note: who cares for VMS these days?
(and how much useless effort has been put in the past,
to support lousy operating systems?)
[instance variables:]
pathName <String> the file's path (if known)
canPosition <Boolean> positionable - read above comment
copyrightCOPYRIGHT (c) 1989 by Claus Gittinger
All Rights Reserved
This software is furnished under a license and may be used
only in accordance with the terms of that license and with the
inclusion of the above copyright notice. This software may not
be provided or otherwise made available to, or used by, any
other person. No title to or ownership of the software is
hereby transferred.
Compatibility-ANSI
-
write: filename
-
return a FileStream for new file named filename, aString.
If the file exists, it is truncated, otherwise created.
The file is opened for read/write access.
Same as newFileNamed: for ANSI compatibilily
Compatibility-Dolphin
-
read: filename text: text
-
return a readonly FileStream for the existing file named filename, aString.
If the argument, text is false, the stream is setup to read binary bytes,
if false, it reads characters.
-
write: filename mode: modeSymbol
-
return a writable FileStream for the file named filename, aString.
The modeSymbol controls how the file is opened; currently supported are:
#append
-
write: filename text: textModeBoolean
-
return a writable FileStream for the file named filename, aString.
If the argument, text is false, the stream is setup to write binary bytes,
if false, it writes characters.
Compatibility-Squeak
-
fileIn: aFilenameOrString
-
Modified (format): / 15-03-2021 / 13:13:03 / cg
-
forceNewFileNamed: filename
-
return a writing FileStream for new file named filename, aString.
If it already exists, it is overwritten silently.
-
oldFileOrNoneNamed: fileNameOrString
( an extension from the stx:libcompat package )
-
If the file exists, answer a read-only FileStream on it.
If it doesn't, answer nil.
Usage example(s):
FileStream oldFileOrNoneNamed:'foo' -> nil
(FileStream oldFileOrNoneNamed:'Makefile') close
|
-
readOnlyFileNamed: filename
-
return a readonly FileStream for the existing file named filename, aString.
-
readOnlyFileNamed: filename do: aBlock
-
open a readonly stream on filename and evaluate aBlock with it.
Return the value from aBlock.
Ensures that the stream is closed afterwards
-
readonlyFileNamed: filename do: aBlock
( an extension from the stx:libcompat package )
-
open a readonly stream on filename and evaluate aBlock with it.
Ensures that the stream is closed afterwards
Compatibility-VW
-
badArgumentsSignal
-
Signal constants
-
userInitiatedFileSaveQuerySignal
-
return the query signal, which is raised before a user-initiated
file-save / file-saveAs operation is performed.
The query will be invoked with the fileName which is about to be
written to.
The default signal here returns true, which will grant the save.
End-user applications may want to catch this signal,
and only return true for certain directories.
class initialization
-
initialize
-
(comment from inherited method)
self patchByteOrderOptimizedMethods
instance creation
-
appendingOldFileNamed: filename
-
return a FileStream for existing file named filename, aString.
The file is opened for writeonly access.
Usage example(s):
FileStream appendingOldFileNamed:'adasdasasd'
|
-
appendingOldFileNamed: filename in: aDirectory
-
return a FileStream for existing file named filename, aString
in aDirectory, a FileDirectory.
The file is opened for writeonly access.
-
fileNamed: filename
-
return a stream on file filename - if the file does not
already exist, create it.
The file is opened for read/write access.
-
fileNamed: filename in: aDirectory
-
return a stream on file filename - if the file does not
already exist, create it.
The file is opened for read/write access.
-
newFileForWritingNamed: filename
-
return a FileStream for new file named filename, aString.
If the file exists, it is truncated, otherwise created.
The file is opened for writeonly access.
-
newFileForWritingNamed: filename in: aDirectory
-
return a FileStream for new file named filename, aString
in aDirectory, a FileDirectory.
If the file exists, it is truncated, otherwise created.
The file is opened for writeonly access.
-
newFileNamed: stringOrFilename
-
return a FileStream for new file named stringOrFilename, a String or a Filename.
If the file exists, it is truncated, otherwise created.
The file is opened for read/write access.
-
newFileNamed: filename in: aDirectory
-
return a FileStream for new file named filename, aString
in aDirectory, a FileDirectory.
If the file exists, it is truncated, otherwise created.
The file is opened for read/write access.
-
newTemporary
-
create atomically a new file and return the file stream - use this for temporary files.
The created file has the name '/tmp/stxtmp_xx_nn' where xx is our
unix process id, and nn is a unique number, incremented with every call to this method.
If any of the environment variables STX_TMPDIR, ST_TMPDIR, TMPDIR is set,
its value defines the temp directory.
Usage example(s):
FileStream newTemporary
FileStream newTemporary
|
-
newTemporaryIn: aDirectoryOrNil
-
create atomically a new file and return the file stream - use this for temporary files.
The created file is in aDirectoryPrefix and named 'stxtmp_xx_nn',
where xx is our unix process id, and nn is a unique number, incremented
with every call to this method.
Usage example(s):
temp files somewhere
(not recommended - use above since it can be controlled via shell variables):
FileStream newTemporaryIn:'/tmp'
FileStream newTemporaryIn:'/tmp'
FileStream newTemporaryIn:'/usr/tmp'
FileStream newTemporaryIn:'/'
|
Usage example(s):
a local temp file:
FileStream newTemporaryIn:''
FileStream newTemporaryIn:nil
FileStream newTemporaryIn:'.'
FileStream newTemporaryIn:('source' asFilename)
|
-
newTemporaryIn: aDirectoryOrNil nameTemplate: template
-
create atomically a new file and return the file stream - use this for temporary files.
The created file is in aDirectoryOrNil (i.e. the current directory if aDirectoryOrNil is nil)
and named after the given template in which %1 and %2 are expanded to the unix process id,
and a unique number, incremented with every call to this method.
See also: #newTemporary which looks for a good temp directory.
Usage example(s):
temp files in '/tmp':
FileStream newTemporaryIn:'/tmp' asFilename nameTemplate:'foo%1_%2'
Will append a number to the generated filename on the second try:
FileStream newTemporaryIn:'/tmp' asFilename nameTemplate:'foo'
FileStream newTemporaryIn:'c:\temp' asFilename nameTemplate:'foo'
|
Usage example(s):
temp files somewhere
(not recommended - use above since it can be controlled via shell variables):
FileStream newTemporaryIn:'/tmp' nameTemplate:'foo'
FileStream newTemporaryIn:'/tmp' nameTemplate:'foo%1_%2'
FileStream newTemporaryIn:'/tmp' nameTemplate:'foo%1_%2'
FileStream newTemporaryIn:'/usr/tmp' nameTemplate:'foo%1_%2'
FileStream newTemporaryIn:'/' nameTemplate:'foo%1_%2'
|
Usage example(s):
a local temp file:
FileStream newTemporaryIn:'' nameTemplate:'foo%1_%2'
FileStream newTemporaryIn:nil nameTemplate:'foo%1_%2'
FileStream newTemporaryIn:'.' nameTemplate:'foo%1_%2'
FileStream newTemporaryIn:('source' asFilename) nameTemplate:'foo%1_%2'
|
-
newTemporaryIn: aDirectoryOrNil withSuffix: aSuffixString
-
create atomically a new file and return the file stream - use this for temporary files.
The created file is in aDirectoryPrefix and named 'stxtmp_xx_nn',
where xx is our unix process id, and nn is a unique number, incremented
with every call to this method.
Usage example(s):
FileStream newTemporaryWithSuffix:'txt'
FileStream newTemporaryIn:'/tmp' withSuffix:'txt'
|
-
newTemporaryWithSuffix: aString
-
create atomically a new file and return the file stream - use this for temporary files.
The created file has the name '/tmp/stxtmp_xx_nn' where xx is our
unix process id, and nn is a unique number, incremented with every call to this method.
If any of the environment variables STX_TMPDIR, ST_TMPDIR, TMPDIR is set,
its value defines the temp directory.
Usage example(s):
FileStream newTemporaryWithSuffix:'txt'
|
-
oldFileNamed: filename
-
return a FileStream for existing file named filename, aString.
The file is opened for read/write access.
Raises an error if the file does not exist.
Usage example(s):
'/tmp/dAsGiBtEsNiChT' asFilename remove.
FileStream oldFileNamed:'/tmp/dAsGiBtEsNiChT'
|
-
oldFileNamed: filename in: aDirectory
-
return a FileStream for existing file named filename, aString
in aDirectory, a FileDirectory.
The file is opened for read/write access.
Raises an error if the file does not exist.
Usage example(s):
FileStream oldFileNamed:'dAsGiBtEsNiChT' in:'/'
|
-
open: aFilenameString withMode: anArrayOrString
-
The argument de
The file is opened for read/write access.
Raise an exception on error.
Return nil, when proceeding from the error.
-
readonlyFileNamed: filename
-
Return a readonly FileStream for existing file named filename, a String.
Raises an error if the file does not exist.
Usage example(s):
FileStream readonlyFileNamed:'dAsGiBtEsNiChT'
|
-
readonlyFileNamed: filename in: aDirectory
-
return a readonly FileStream for existing file named filename, aString
in aDirectory, a fileName or string instance representing a directory.
Raises an error if the file does not exist.
Usage example(s):
FileStream readonlyFileNamed:'dAsGiBtEsNiChT' in:'/'
FileStream readonlyFileNamed:'dAsGiBtEsNiChT' in:'/' asFilename
|
Compatibility-Squeak
-
fullName
-
Squeak compatibility: return the full pathname
accessing
-
asFilename
-
return the file name
-
baseName
-
return my name without leading direcory-path (i.e. the plain fileName)
as a string
-
contentsOfEntireFile
-
ST-80 compatibility: return contents as a String (or byteArray, if in binary mode).
See also #contents, which returns the lines as stringCollection for text files.
-
directoryName
-
return the name of the directory I'm in as a string
-
fileName
-
return the file name as a Filename.
pathName returns a String for compatibility with other smalltalks
-
name
-
return my path name as a string
-
pathName
-
return the pathname, a String
-
removeOnClose: aBoolean
-
set/clear the removeOnClose flag.
If set, the file will be removed when closed.
Provided mostly for OS's which do not allow an
open file to be removed (i.e. non unixes),
when a fileStream for a tempFile is used.
Especially, the CVS-SourceCodeManager returns
this kind of file-handles occasionally.
This is an ST/X special feature which is not portable
to other systems.
-
store: something
-
what really should this do
file access rights
-
accessRights
-
return the access rights of the file as opaque data
(SmallInteger in unix/linux)
Usage example(s):
'Make.proto' asFilename readingFileDo:[:s|
s accessRights
]
|
-
accessRights: opaqueData
-
set the access rights of the file to opaqueData,
which is normally retrieved by Filename>>#accessRights
or FileStreamm>>#accessRights.
Usage example(s):
'Make.proto' asFilename readingFileDo:[:s|
s accessRights:s accessRights
]
|
Usage example(s):
'/' asFilename readingFileDo:[:s|
s accessRights:s accessRights
]
|
-
addAccessRights: aCollection
-
add the access rights as specified in aCollection for the file represented
by the receiver. The argument must be a collection of symbols,
such as #readUser, #writeGroup etc.
Usage example(s):
'foo' asFilename writeStream
addAccessRights:#(readUser readGroup readOthers); close.
'foo' asFilename writeStream
addAccessRights:#(writeUser writeGroup writeOthers); close.
'foo' asFilename writeStream
addAccessRights:#(executeUser executeGroup executeOthers); close.
|
-
makeExecutable
-
make the file executable - you must have permission to do so.
For directories, execution means: 'allow changing into it'
-
makeExecutableForAll
-
make the file executable for all - you must have permission to do so.
For directories, execution means: 'allow changing into it'
-
makeExecutableForGroup
-
make the file executable for the group - you must have permission to do so.
For directories, execution means: 'allow changing into it'
-
makeReadable
-
make the file readable for the owner - you must have permission to do so.
-
makeReadableForAll
-
make the file readable for all - you must have permission to do so.
-
makeReadableForGroup
-
make the file readable for the group - you must have permission to do so.
-
makeUnwritable
-
make the file unwritable for all - you must have permission to do so.
-
makeWritable
-
make the file writableable for all - you must have permission to do so.
-
makeWritableForAll
-
make the file writable for all - you must have permission to do so.
-
makeWritableForGroup
-
make the file writable for the group - you must have permission to do so.
-
removeAccessRights: aCollection
-
remove the access rights as specified in aCollection for the file represented
by the receiver. The argument must be a collection of symbols,
such as #readUser, #writeGroup etc.
Raises an exception if not successful.
Usage example(s):
'foo' asFilename writeStream
removeAccessRights:#(readUser readGroup readOthers); close.
'foo' asFilename writeStream
removeAccessRights:#(writeUser writeGroup writeOthers); close.
'foo' asFilename writeStream
removeAccessRights:#(executeUser executeGroup executeOthers); close.
|
file operations
-
remove
-
remove the undelying file.
Note: removing does not work in Windows if the file is still opened!
-
truncateTo: newSize
-
truncate the underlying OS file to newSize.
Warning: this may not be implemented on all platforms.
Usage example(s):
|f s|
f := 'testTTTT' asFilename.
s := f writeStream.
s next:1000 put:$a.
s truncateTo:100.
s close.
Transcript showCR:(f fileSize).
f remove.
|
file times
-
setAccessTime: aTimestampOrNow
-
set the access time of the file to aTimestampOrNow.
aTimestampOrNow maybe either a Timestamp or the symbol #now.
Usage example(s):
|fn|
fn := FileStream newTemporary
setAccessTime:(Timestamp readFrom:'1988-07-01');
close;
asFilename.
fn accessTime
|
-
setModificationTime: aTimestampOrNow
-
set the modification time of the file to aTimestampOrNow.
aTimestampOrNow maybe either a Timestamp or the symbol #now.
Usage example(s):
|fn|
fn := FileStream newTemporary
setModificationTime:(Timestamp readFrom:'1980-07-01');
close;
asFilename.
fn modificationTime
|
finalization
-
executor
-
keep the pathname for any FileStream
inspecting
-
inspectorExtraMenuOperations
( an extension from the stx:libtool package )
-
extra operation-menu entries to be shown in an inspector.
Answers a collection of pairs containing aString and action aBlock.
aString is the label of the menu item.
aBlock is evaluated when the menu item is selected.
misc functions
-
syncFileSystem
-
sync the filesystem containing this FileStream
positioning
-
position
-
return the read/write position in the file
-
position: newPos
-
set the read/write position in the file
-
reset
-
additionaly to setting the position to the beginning of the file,
re-open a previously closed file. This behavior is compatible
with other Smalltalk dialects
-
setToEnd
-
set the read/write position in the file to be at the end of the file
-
slowPosition: newPos
-
position the file by re-reading everything up-to newPos.
The effect is the same as that of #position:, but its much slower.
This is required to reposition nonPositionable streams, such
as tape-streams or variable-record-RMS files under VMS.
Caveat:
This should really be done transparently by the stdio library.
printing & storing
-
printOn: aStream
-
append a user printed representation of the receiver to aStream.
The format is suitable for a human - not meant to be read back.
-
storeOn: aStream
-
append a representation of the receiver to aStream,
from which a copy can be reconstructed later.
private
-
protected closeFile
-
low level close - may be redefined in subclasses.
Don't send this message, send #close instead
-
createForReadWrite
-
create/truncate the file for read/write.
If the file existed, it's truncated; otherwise it's created.
Raise an exception on error.
Return nil, when proceeding from the error, self otherwise.
-
createForWriting
-
create/truncate the file for writeonly.
If the file existed, it's truncated; otherwise it's created.
Raise an exception on error.
Return nil, when proceeding from the error, self otherwise.
-
openFile: pathNameStringArg withMode: openmode attributes: attributeSpec
-
open the file;
openmode is the string defining the way to open as defined by the stdio library
(i.e. the 2nd fopen argument).
attributeSpec is an additional argument, only used with VMS - it allows a file to
be created as fixedRecord, variableRecord, streamLF, streamCR, ...
In VMS, if nonNil, it must consist of an array of strings (max:10), giving additional
attributes (see fopen description).
Passing a nil specifies the default format (streamLF) - ST/X always invokes this with nil.
This argument is ignored in UNIX & MSDOS systems.
This is a private entry, but maybe useful to open/create a file in a special mode,
which is proprietrary to the operatingSystem.
Usage example(s):
self new openFile:'C:\Windows\System32\drivers\etc\hosts' withMode:'rb' attributes:#().
self new openFile:'C:\Windows\System32\drivers\etc\hosts' asUnicode16String withMode:'rb' attributes:#().
|
-
openForAppending
-
open the file for writeonly appending to the end.
If the file does not exist, raise OpenError;
otherwise return the receiver.
Return nil, when proceeding from the error
-
openForReadWrite
-
open the file for read/write.
If the file does not exist, raise OpenError;
otherwise return the receiver.
Return nil, when proceeding from the error
-
openForReading
-
open the file for readonly.
If the file does not exist, raise OpenError;
otherwise return the receiver.
Return nil, when proceeding from the error
-
openForWriting
-
open the file writeonly. The contents of the file is preserved.
If the file does not exist, raise OpenError;
otherwise return the receiver.
Return nil, when proceeding from the error
-
openWithMode: openmode
-
open the file;
openmode is the string defining the way to open as defined by the stdio library
(i.e. the 2nd fopen argument).
Raise an exception on error.
Return nil, when proceeding from the error, self otherwise.
This is a private entry, but maybe useful to open a file in a special mode,
which is proprietrary to the operatingSystem.
-
openWithMode: openmode attributes: attributeSpec
-
open the file;
openmode is the string defining the way to open as defined by the stdio library
(i.e. the 2nd fopen argument).
attributeSpec is an additional argument, only used with VMS - it allows a file to
be created as fixedRecord, variableRecord, streamLF, streamCR, ...
In VMS, if nonNil, it must consist of an array of strings (max:10), giving additional
attributes (see fopen description).
Passing a nil specifies the default format (streamLF) - ST/X always invokes this with nil.
This argument is ignored in UNIX & MSDOS systems.
This is a private entry, but maybe useful to open/create a file in a special mode,
which is proprietrary to the operatingSystem.
Raise an exception on error.
Return nil, when proceeding from the error, self otherwise.
-
pathName: aStringOrFilename
-
set the pathname
-
pathName: aStringOrFilename in: aDirectory
-
set the pathname starting at aDirectory, a FileDirectory
-
reOpen
-
USERS WILL NEVER INVOKE THIS METHOD
sent after snapin to reopen streams.
-
setMode: aModeSymbol
-
-
setPathName: pathNameString removeOnClose: aBoolean
-
private fileIn
-
fileInNotifying: notifiedLoader passChunk: passChunk
-
central method to file in from the receiver, i.e. read chunks and evaluate them -
return the value of the last chunk.
Someone (which is usually some codeView) is notified of errors.
queries
-
collectionSize
-
common stream protocol: return the size of the stream;
that's the number of bytes of the file.
-
fileSize
-
return the size in bytes of the file
-
remainingSize
-
return the number of remaining elements to read in the streamed collection.
-
size
-
common stream protocol: return the size of the stream;
that's the number of bytes of the file.
rel5 protocol
-
positionFile: handle position: newPos
-
for migration to rel5 only
stream-to-stream copy
-
copy: numberOfBytesOrNil into: outStream bufferSize: bufferSize
-
read from the receiver, and write numberOfBytes data to another aWriteStream.
Return the number of bytes which have been transferred.
If nuberOfBytesOrNil is nil, copy until the end of myself.
Redefined to use operating system features to do a fast copy.
testing
-
isDirectory
-
-
isEmpty
-
common stream protocol: are there no bytes in the file?
-
isFileStream
-
return true, if the receiver is some kind of fileStream.
redefined from Object
for VMS users only:
The #openWithMode:attributes: entry allows additional RMS attributes
to be passed in the second argument, which must be an array of strings
as described in the 'creat' RTL Library documentation.
For example, to create a file with fixed records and recordLength of 100,
use:
|newFile|
newFile := FileStream new pathName:'<nameOfFile>'.
newFile setMode:#writeonly.
newFile openWithMode:'w' attributes:#('rfm=fix' 'fsz=100').
since all of the above is private protocol, and it is considered bad style to
access these from user programs, we recommend subclassing FileStream as
something like VMSFixedRecordFileStream, and redefine the instance creation
method(s) there as appropriate.
This will retain VMS specifics in one place and enhance maintanability.
|