FileStream.st
author claus
Thu, 02 Jun 1994 18:22:49 +0200
changeset 88 81dacba7a63a
parent 85 1343af456e28
child 92 0c73b48551ac
permissions -rw-r--r--
*** empty log message ***

"
 COPYRIGHT (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.
"

ExternalStream subclass:#FileStream
       instanceVariableNames:'pathName'
       classVariableNames:''
       poolDictionaries:''
       category:'Streams-External'
!

FileStream comment:'
COPYRIGHT (c) 1989 by Claus Gittinger
              All Rights Reserved
'!

!FileStream class methodsFor:'documentation'!

copyright
"
 COPYRIGHT (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.
"
!

version
"
$Header: /cvs/stx/stx/libbasic/FileStream.st,v 1.13 1994-06-02 16:20:18 claus Exp $
"
!

documentation
"
    This class provides access to the operating systems underlying file
    system (i.e. its an interface to the stdio library).
"
! !

%{
#include <stdio.h>
#include <errno.h>

#ifdef transputer
# include <iocntrl.h>
# ifndef fileno
   /* kludge: inmos forgot fileno */
#  define fileno(f)     ((f)->__file)
# endif
#else
# include <sys/types.h>
# include <sys/stat.h>
#endif

#ifdef hpux
# define fileno(f)      ((f->__fileH << 8) | (f->__fileL))
#endif

#ifndef SEEK_SET
# define SEEK_SET       0
#endif
#ifndef SEEK_CUR
# define SEEK_CUR       1
#endif
#ifndef SEEK_END
# define SEEK_END       2
#endif

%}

!FileStream class methodsFor:'instance creation'!

newFileNamed:filename
    "return a FileStream for new file named filename, aString.
     If the file exists, it is truncated, otherwise created.
     The file is opened for write access only."

    |newStream|
    newStream := self new pathName:filename.
    newStream createForReadWrite isNil ifTrue:[^nil].
    ^ newStream
!

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 write access only."

    |newStream|
    newStream := self new pathName:filename in:aDirectory.
    newStream createForReadWrite isNil ifTrue:[^nil].
    ^ newStream
!

oldFileNamed:filename
    "return a FileStream for existing file named filename, aString.
     The file is opened for read/write access."

    |newStream|

    (OperatingSystem isReadable:filename) ifFalse:[^nil].
    newStream := self new pathName:filename.
    newStream readwrite.
    newStream openForReadWrite isNil ifTrue:[^nil].
"
    this is not a good idea; someone else might be appending ...

    newStream readLimit:(newStream size).
"
    ^ newStream
!

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."

    |newStream|
    newStream := self new pathName:filename in:aDirectory.
    newStream openForReadWrite isNil ifTrue:[^nil].
"
    this is not a good idea; someone else might be appending ...

    newStream readLimit:(newStream size).
"
    ^ newStream
!

fileNamed:filename
    "return a stream on file filename - if the file does not
     already exist, create it."

    |stream|

    stream := self oldFileNamed:filename.
    stream isNil ifTrue:[
        stream := self newFileNamed:filename
    ].
    ^ stream
!

fileNamed:filename in:aDirectory
    "return a stream on file filename - if the file does not
     already exist, create it."

    |stream|

    stream := self oldFileNamed:filename in:aDirectory.
    stream isNil ifTrue:[
        stream := self newFileNamed:filename in:aDirectory
    ].
    ^ stream
!

readonlyFileNamed:filename
    "return a readonly FileStream for existing file named filename, aString"

    |newStream|

    (OperatingSystem isReadable:filename) ifFalse:[^nil].

    newStream := self new pathName:filename.
    newStream openForReading isNil ifTrue:[^nil].
"
    this is not a good idea; someone else might be appending ...

    newStream readLimit:(newStream size).
"
    ^ newStream
!

readonlyFileNamed:filename in:aDirectory
    "return a readonly FileStream for existing file named filename, aString
     in aDirectory, a FileDirectory"

    |newStream|
    newStream := self new pathName:filename in:aDirectory.
    newStream openForReading isNil ifTrue:[^nil].
"
    this is not a good idea; someone else might be appending ...

    newStream readLimit:(newStream size).
"
    ^ newStream
!

appendingOldFileNamed:filename
    "return a FileStream for existing file named filename, aString"

    |newStream|
    newStream := self new pathName:filename.
    newStream openForAppending isNil ifTrue:[^nil].
"
    this is not a good idea; I might like to read the written stuff ...

    newStream readLimit:(newStream size).
"
    ^ newStream
!

appendingOldFileNamed:filename in:aDirectory
    "return a FileStream for existing file named filename, aString
     in aDirectory, a FileDirectory"

    |newStream|
    newStream := self new pathName:filename in:aDirectory.
    newStream openForAppending isNil ifTrue:[^nil].
"
    this is not a good idea; I might like to read the written stuff ...

    newStream readLimit:(newStream size).
"
    ^ newStream
! !

!FileStream methodsFor:'accessing'!

store:something
    "what really should this do"

    self nextPutAll:something storeString
!

directoryName
    "return the name of the directory I'm in"

    |path lastIndex index|

    path := pathName.
    lastIndex := 0.
    index := path indexOf:$/.
    [index ~~ 0] whileTrue:[
        lastIndex := index.
        index := path indexOf:$/ startingAt:(index + 1)
    ].
    (lastIndex == 0) ifTrue:[^ '.'].
    (lastIndex == 1) ifTrue:[^ '/'].
    ^ path copyTo:(lastIndex - 1)
!

name
    "return my name without leading direcory-path"

    |lastIndex index|

    lastIndex := 1.
    [true] whileTrue:[
        index := pathName indexOf:$/ startingAt:lastIndex.
        (index == 0) ifTrue:[
            ^ pathName copyFrom:lastIndex
        ].
        lastIndex := index + 1
    ]
!

pathName
    "return the pathname"

    ^ pathName
! !

!FileStream methodsFor:'private'!

pathName:filename
    "set the pathname"

    pathName := filename
!

pathName:filename in:aDirectory
    "set the pathname starting at aDirectory, a FileDirectory"

    ((filename at:1) == $/) ifTrue:[
        "filename may not start with a '/'"
        pathName := nil
    ] ifFalse:[
        pathName := aDirectory pathName.
        (pathName endsWith:'/') ifFalse:[
            pathName := pathName , '/'
        ].
        pathName := pathName , filename
    ]
!

open
    "open the file"

    pathName isNil ifTrue:[^nil].
    (mode == #readonly) ifTrue: [
        ^ self openWithMode:'r'
    ].
    (mode == #writeonly) ifTrue: [
        ^ self openWithMode:'w'
    ].
    ^ self openWithMode:'r+'
!

openWithMode:openmode
    "open the file; openmode is the string defining the way to open"

    |retVal|
%{
    FILE *f;
    OBJ path;
    extern OBJ Filename;
    extern errno;

    if (_INST(filePointer) == nil) {
        path = _INST(pathName);
        if (path != nil 
         && ((_qClass(path)==String) || (_qClass(path) == Filename))) {
            do {
#ifdef LINUX
                /* LINUX returns a non-NULL f even when interrupted */
                errno = 0;
                f = (FILE *) fopen((char *) _stringVal(path), (char *) _stringVal(openmode));
                if (errno == EINTR)
                    f = NULL;
#else

                f = (FILE *) fopen((char *) _stringVal(path), (char *) _stringVal(openmode));
#endif
            } while ((f == NULL) && (errno == EINTR));
            if (f == NULL) {
                ExternalStream_LastErrorNumber = _MKSMALLINT(errno);
                _INST(position) = nil;
            } else {
                _INST(filePointer) = MKOBJ((int)f);
                _INST(position) = _MKSMALLINT(1);
                retVal = self;
            }
        }
    }
%}
.
    retVal notNil ifTrue:[
        buffered := true.       "default is buffered"
        Lobby register:self
    ].
    ^ retVal
!

openForReading
    "open the file for readonly.
     If the file does not exist its an error, return nil; 
     otherwise return the receiver."

    mode := #readonly.
    ^ self openWithMode:'r'
!

openForWriting
    "open the file writeonly.
     If the file does not exist its an error, return nil; 
     otherwise return the receiver."

    mode := #writeonly.
    ^ self openWithMode:'r+'   "unix-io does not allow this; open for update here"
!

openForAppending
    "open the file for writeonly appending to the end.
     If the file does not exist its an error, return nil; 
     otherwise return the receiver."

    mode := #writeonly.
    ^ self openWithMode:'a+'
!

openForReadWrite
    "open the file for read/write.
     If the file does not exist its an error, return nil; 
     otherwise return the receiver."

    mode := #readwrite.
    ^ self openWithMode:'r+'
!

createForWriting
    "create/truncate the file for writeonly.
     If the file existed, its truncated; otherwise its created."

    mode := #writeonly.
    ^ self openWithMode:'w'
!

createForReadWrite
    "create/truncate the file for read/write.
     If the file existed, its truncated; otherwise its created."


    mode := #readwrite.
    ^ self openWithMode:'w+'
!

reOpen
    "sent after snapin to reopen streams"

    filePointer notNil ifTrue:[
        "it was open, when snapped-out"
        filePointer := nil.
        Lobby unregister:self.
        self open.
        filePointer isNil ifTrue:[
            "this happens, if after a restart, the file is no longer accessable ..."

            ('could not reopen file: ', pathName) errorPrintNewline.
        ] ifFalse:[
            self position:position.
        ]
    ]
! !

!FileStream methodsFor:'queries'!

size
    "return the size in bytes of the file"

%{  /* NOCONTEXT */

#ifdef transputer
    FILE *f;
    int size;

    if (_INST(filePointer) != nil) {
        f = (FILE *)MKFD(_INST(filePointer));
        if ((size = filesize(fileno(f))) >= 0) {
            RETURN ( _MKSMALLINT(size) );
        }
    }
#else
    FILE *f;
    struct stat buf;
    int ret;
    extern errno;
    int fd;

    if (_INST(filePointer) != nil) {
        f = (FILE *)MKFD(_INST(filePointer));
        fd = fileno(f);
        do {
            ret = fstat(fd, &buf);
        } while ((ret < 0) && (errno == EINTR));
        if (ret >= 0) {
            RETURN ( _MKSMALLINT(buf.st_size) );
        }
        ExternalStream_LastErrorNumber = _MKSMALLINT(errno);
    }
#endif
%}
.
    "could add a fall-back here:

        oldPosition := self position.
        self setToEnd.
        sz := self position.
        self position:oldPosition.
        ^ sz
    "
    filePointer isNil ifTrue:[^ self errorNotOpen].
    ^ self primitiveFailed
!

position
    "return the read/write position in the file -
     notice, in smalltalk indices start at 1 so begin of file is 1"

%{  /* NOCONTEXT */

    FILE *f;
    long currentPosition;
    extern errno;

    if (_INST(filePointer) != nil) {
        f = (FILE *)MKFD(_INST(filePointer));
        do {
            if (_INST(buffered) == true) {
                currentPosition = (long) ftell(f);
            } else {
                currentPosition = (long) lseek(fileno(f), 0L, SEEK_CUR);
            }
        } while ((currentPosition < 0) && (errno == EINTR));
        if (currentPosition >= 0) {
            /*
             * notice: Smalltalk index starts at 1
             */
            RETURN ( _MKSMALLINT(currentPosition + 1) );
        }
        ExternalStream_LastErrorNumber = _MKSMALLINT(errno);
    }
%}
.
    filePointer isNil ifTrue:[^ self errorNotOpen].
    ^ self primitiveFailed
!

position:newPos
    "set the read/write position in the file"

%{  /* NOCONTEXT */

    FILE *f;
    int ret;
    extern errno;

    if (_INST(filePointer) != nil) {
        if (_isSmallInteger(newPos)) {
            f = (FILE *)MKFD(_INST(filePointer));
            /*
             * notice: Smalltalk index starts at 1
             */
            do {
                if (_INST(buffered) == true) {
                    ret = fseek(f, (long) (_intVal(newPos) - 1), SEEK_SET);
                } else {
                    ret = (long) lseek(fileno(f), (long)(_intVal(newPos) - 1), SEEK_SET);
                }
            } while ((ret < 0) && (errno == EINTR));
            if (ret >= 0) {
                _INST(position) = newPos;
                /*
                 * just to make certain ...
                 */
                _INST(hitEOF) = false;
                RETURN ( self );
            }
            ExternalStream_LastErrorNumber = _MKSMALLINT(errno);
        }
    }
%}
.
    filePointer isNil ifTrue:[^ self errorNotOpen].
    ^ self primitiveFailed
!

setToEnd
    "set the read/write position in the file to be at the end of the file"

%{
    FILE *f;
    int ret;
    extern errno;

    if (_INST(filePointer) != nil) {
        f = (FILE *)MKFD(_INST(filePointer));
        _INST(position) = nil;
        do {
            if (_INST(buffered) == true) {
                ret = fseek(f, 0L, SEEK_END);
            } else {
                ret = (long)lseek(fileno(f), 0L, SEEK_END);
            }
        } while ((ret < 0) && (errno == EINTR));
        if (ret >= 0) {
            RETURN ( self );
        }
        ExternalStream_LastErrorNumber = _MKSMALLINT(errno);
    }
%}
.
    filePointer isNil ifTrue:[^ self errorNotOpen].
    DemoMode ifTrue:[^ self warn:'no save in Demo mode'].
    ^ self primitiveFailed
! !

!FileStream methodsFor:'testing'!

isFileStream
    "return true, if the receiver is some kind of fileStream.
     redefined from Object"

    ^ true
! !

!FileStream methodsFor:'printing & storing'!

printOn:aStream
    aStream nextPutAll:'(a FileStream for:'.
    aStream nextPutAll:pathName.
    aStream nextPut:$)
!

storeOn:aStream
    aStream nextPutAll:'(FileStream oldFileNamed:'.
    aStream nextPutAll:pathName.
    (self position ~~ 1) ifTrue:[
        aStream nextPutAll:'; position:'.
        self position storeOn:aStream
    ].
    aStream nextPut:$)
! !