10.5 File Streams

File streams are streams associated with files. An input file stream reads the characters it delivers from a file, an output file stream prints the characters it receives to a file. The following functions can be used to create such streams. They return fail if an error occurred, in this case LastSystemError (see LastSystemError) can be used to get information about the error.

  • InputTextFile( name-file ) O

    InputTextFile( name-file ) returns an input stream in the category IsInputTextStream that delivers the characters from the file name-file.

  • OutputTextFile( name-file, append ) O

    OutputTextFile( name-file, append ) returns an output stream in the category IsOutputTextFile that writes received characters to the file name-file. If append is false, then the file is emptied first, otherwise received characters are added at the end of the list.

    Example

    # use a temporary directory
    gap> name := Filename( DirectoryTemporary(), "test" );;
    
    # create an output stream, append output, and close again
    gap> output := OutputTextFile( name, true );;
    gap> AppendTo( output, "Hallo\n", "You\n" );
    gap> CloseStream(output);
    
    # create an input, print complete contents of file, and close
    gap> input := InputTextFile(name);;
    gap> Print( ReadAll(input) );
    Hallo
    You
    gap> CloseStream(input);
    
    # append a single line
    gap> output := OutputTextFile( name, true );; 
    gap> AppendTo( output, "AppendLine\n" );
    
    # close output stream to flush the output
    gap> CloseStream(output);
    
    
    # create an input, print complete contents of file, and close
    gap> input := InputTextFile(name);;
    gap> Print( ReadAll(input) );
    Hallo
    You
    AppendLine
    gap> CloseStream(input);
    

    [Top] [Previous] [Up] [Next] [Index]

    GAP 4 manual
    February 2000