User Tools

Site Tools


k6:k6.5:start

6.5 Class File

This class is used for

  • the representation of a file opened with the OPEN() command,
  • accessing standard input, output and error streams,
  • opening and saving a file,
  • manipulating file paths with the static methods of the File class.

You cannot directly create this class. You must use the OPEN statement.

6.5.1 Properties

The File class has these properties:

PropertyData typeDescription
Blocking BooleanReturns or sets the truth value True if the stream is blocked. If this property is set to True, reading from the stream is blocked if there is nothing to read. Writing to the stream is blocked if, for example, the internal system buffer is full.
ByteOrder IntegerReturns the byte order or sets the byte order used to read or write binary data to the stream. The property can take the following values: gb.BigEndian as “Big endian byte order” or gb.LittleEndian as “Little endian byte order”.
EndOfFileBooleanThis property signals whether the last use of LINE INPUT has reached the end of the file instead of reading an entire line with an end-of-line character.
EndOfLine IntegerReturns or sets the line break separator used by the current stream. The possible values are: gb.Unix for lines separated by Chr$(10), gb.Windows for lines separated by Chr$(13) and Chr$(10), gb.Mac for lines separated by Chr$(13). The value of this property is used by LINE INPUT, PRINT and the Stream.Lines property. Note that you can read both Unix and Windows line formats with gb.Unix. But it only writes the Unix format!
Handle IntegerReturns the system file descriptor associated with the current stream.
IsTermBooleanReturns True if a stream is associated with a terminal.
Lines .Stream.LinesReturns a virtual object (type string array) with which you can read a stream line by line.
TagVariantReturns the value of the Tag property assigned to the stream or sets the value. This property of data type Variant is intended for free use by the programmer and is not used by the component.
Term.Stream.TermReturns a virtual object that can be used to manage the terminal associated with the stream. The virtual class Stream.Term (gb) has the properties Echo, FlowControl, Height, Width and Name and the method Resize. Link: http://gambaswiki.org/wiki/comp/gb/.stream.term

Table 6.5.1.1 : Properties of the class File

Example of the use of the Lines property:

Dim hStream As Stream
Dim aString As String
...
For Each aString In hStream.Lines
  ...
Next

6.5.2 Static properties

The File class has these three static properties:

PropertyData typeDescription
InFileReturns the standard input stream.
OutFileDelivers the standard output stream.
ErrFileDelivers the standard error output stream.

Table 6.5.2.1 : Static properties of the class File

For appropriate information, see the page: https://wiki.ubuntuusers.de/Shell/Umleitungen for the following example. It shows how to read and write on standard input, standard output and standard error output and presents the use of the static properties File.In, File.Out and File.Err. Each line written on standard input is returned first on standard output and then on standard error output.

Public Sub Main()
  Dim inputLine As String
  ' Loop until the end of the standard input file stream
  While Not Eof(File.In)
    ' Read a line from standard input
    Line Input #File.In, inputLine ' Read data
    ' Print to standard output
    Print #File.Out, inputLine ' Write data
    ' Print to standard error
    Print #File.Err, inputLine ' Write data
  Wend
End

Create a project (command line application ioe (input output error)) and place the above code in the Main.module file. When you run this program in the Gambas IDE, the application seems to hang. If you type some text in the console window of the IDE and press enter, each line is returned twice in the console. However, since the application never sees the end of the file for the standard input stream, you have to stop the project. To get a better idea of what the example does, create a Gambas executable and name it ioe.gambas. Open a terminal and change to the directory where you saved the executable.

If you enter the following command:

ls -a | ./ioe.gambas

you will see each output line of the ls -a command, but always twice. Once from the standard output (stdout) and once from the standard error output (stderr). However, the application now sees the end of the standard input stream and thus ends correctly. With the command

ls -a | ./ioe.gambas > files.txt

you redirect the standard output stream of the ls -a command to a file on the one hand and you see the standard error output stream in the terminal window on the other.

6.5.3 Methods

The File class has these six methods:

MethodReturnTypeDescription
Begin()-Starts buffering the data written to the stream so that when the Send method is called, everything is sent at once.
Close()-Closes the stream. The method is exactly the same as the CLOSE statement.
Drop()-Deletes the data buffered since the last call of the Begin() method.
ReadLine([ Escape As String ]) StringReads a line of text from the stream, just like the LINE INPUT statement. If Escape is specified, line breaks between two escape characters are ignored. This method is very useful when reading CSV files.
Send()-Sends all data at once that has been buffered since the last call of the Begin() method.
Watch ( Mode As Integer, Watch As Boolean )-Starts or stops watching the stream file descriptor for reading or writing after it has been opened. Mode is the observation type: gb.Read to observe while reading or gb.Write to observe while writing. Watch is TRUE to enable watching and FALSE to disable watching.

Table 6.5.3.1 : Methods of the class File

6.5.4 Events

The class has these two selected events, among others:

EventDescription
Read()This event is triggered when something is to be read from the file. The file must have been opened with the keyword WATCH for this purpose. See OPEN for more details.
Write()This event is triggered when writing to the file is possible. The file must have been opened with the keyword WATCH. See OPEN for more details.

Table 6.5.4.1 : Events of the File class

6.5.5 Static methods

Of particular interest are the following (static) methods - especially the Load() and Save() methods:

MethodDescription
BaseName( Path As String )Returns the name of a file without extension.
SetBaseName( Path As String, NewBaseName As String )Replaces only the base name of a path and returns the changed path.
Dir( Path As String )Returns the directory part of a file path.
SetDir( Path As String, NewDir As String )Replaces only the directory part of a path and returns the changed path.
Ext( Path As String )Returns the extension (without dot) of a file name.
SetExt( Path As String, NewExt As String )Replaces only the extension of a path and returns the changed path.
Name( Path As String )Returns the complete file name with extension of a file path.
SetName( Path As String, NewName As String ) Replaces the file name of a path and returns the changed path.
Load( FilePath As String )Loads a file and returns its content as string.
Save( FilePath As String, Data As String )Saves the content of a string (Data) to a file with the path FilePath.
IsHidden ( Path As String )Returns True if a file path is hidden. Path is the file path to be checked. A file path is hidden if it itself or one of its parent directories is hidden. Under UNIX, hidden files or directories are those whose name begins with a dot.
IsRelative ( Path As String )Returns True if Path is a relative path. A relative path is a path that does not begin with the / or ~ character.

Table 6.5.5.1 : Static methods of the class File

6.5.6 Examples - Using selected methods of the File class

6.5.6.1 Example 1 - Displaying file path properties

Public Sub btnDisplayProperties_Click()
  If Dialog.OpenFile() Then Return
  Print "Datei-Pfad: " & Dialog.Path
  Print "Verzeichnis der Datei: " & File.Dir(Dialog.Path)
  Print "Dateiname (mit Extension): " & File.Name(Dialog.Path)
  Print "Dateiname (ohne Extension): " & File.BaseName(Dialog.Path)
  Print "Datei-Extension (ohne Punkt): " & File.Ext(Dialog.Path)
End

6.5.6.2 Example 2 - File.Load(Path) and File.Save(Path)

You can use file filters in a file open or file save dialogue. With regular expressions, however, you can set the filters in a much more differentiated way:

  • Dialog.Title = “Import a text file!”
  • Dialog.Filter = [“tb*.txt”, “text files”] ' filename starts with tb
  • Dialog.Filter = [“[0-9]*.txt”, “Text Files”] ' filename starts with a digit
  • Dialog.Filter = [“tb[1-3]*.txt; ta[1-3]*.log”, “Text Files”]

The last filter selects all files in the current directory that begin with the letter string 'tb', which is followed by a digit from the range 1-3, and then a sequence of arbitrary characters. The extension is either .txt or .log.For example, a filter of the following type is often used for text files:

Private $sCurrentFilePath As String
 
Public Sub btnFileLoad_Click()
 
  Dialog.Filter = ["*.txt;*.log;*.xml;*.conf", "Text files"]
  If Dialog.OpenFile() Then Return
  $sCurrentFilePath =  Dialog.Path
 
  txaTextArea.Text = File.Load(Dialog.Path)
  Catch
    Message.Info(Error.Text)
 
End
 
Public Sub btnFileSave_Click()
 
  If Dialog.SaveFile() Then Return
 
  File.Save(Dialog.Path, txaTextArea.Text)
  Catch
    Message.Info(Error.Text)
 
End

6.5.6.3 Example 3 - Using selected static methods of the class File

Dim filePath As String
 
Print "* A standard type of path"
  filePath = "/my/path/file.ext"
Print filePath
Print File.SetBaseName(filePath, "new-name")
 
Print "\\n* Try a path with two extensions"
  filePath = "/my/path/file.ext1.ext2"
Print filePath
Print File.SetBaseName(filePath, "new-name")
 
Print "\\n* A path with just an extension"
  filePath = ".ext"
Print filePath
Print File.SetBaseName(filePath, "new-name")
 
Print "\\n* A path without a file name"
  filePath = "/my/path/.ext"
Print filePath
Print File.SetBaseName(filePath, "new-name")
 
Print "\\n* A path without a file name or extension"
  filePath = "/my/path/"
Print filePath
Print File.SetBaseName(filePath, "new-name")

Outputs in the console of the IDE:

* A standard type of path
/my/path/file.ext
/my/path/new-name.ext
 
* Try a path with two extensions
/my/path/file.ext1.ext2
/my/path/new-name.ext2
 
* A path with just an extension
.ext
new-name.ext
 
* A path without a file name
/my/path/.ext
/my/path/new-name.ext
 
* A path without a file name or extension
/my/path/
/my/path/new-name

6.5.6.4 Project - Controlling a Player

Using the following source code, output text to the console using File.Out and control the music player using the standard input File.In.

To start the player in a console from the project directory:

hans@mint-183 ~/GB3BUCH/6K_Stream/.../MusicPlayer $ gbr3 ./music_player_console.gambas

Source code:

' Gambas module file
 
' Characters are read in via the standard input (terminal) in order to control the MediaPlayer.
Notes: http://www.mplayerhq.hu/DOCS/man/de/mplayer.1.html
 
Public mPlayer As New MediaPlayer
 
Public Sub Main()
 If mPlayer Then mPlayer = zero
 Start()
End
 
Public Sub Start()
 
  mPlayer = New MediaPlayer
  mPlayer.URL = "http://mp3channels.webradio.rockantenne.de/classic-perlen"
  mPlayer.Audio.Volume = +1.0
  mPlayer.Play()
 
  Print #File.Out, ""
  Print #File.Out, "-------------------------------------"
  Print #File.Out, "Instructions for use"
  Print #File.Out, "-------------------------------------"
  Print #File.Out, "+  ▶ Audio.Volume ▲"
  Print #File.Out, "-  ▶ Audio.Volume ▼"
  Print #File.Out, "p  ▶ Player.Pause"
  Print #File.Out, "r  ▶ Player.Run (After a pause)"
  Print #File.Out, "m  ▶ Audio.Mute (off/on)"
  Print #File.Out, "q  ▶ Player.Stop"
  Print #File.Out, "-------------------------------------"
  Print #File.Out, "Each command is followed by <ENTER>."
  Print #File.Out, "-------------------------------------"
  Print #File.Out, ""
 
End
 
Public Sub Application_Read()
 
  Dim sInput As String
  Dim fDeltaVolume As Float
 
  If mPlayer.Audio.Volume > 1.1 Then
    fDeltaVolume = 1.0
  Else
    fDeltaVolume = 0.1
  EndIf
 
  Line Input #File.In, sInput
 
  Select Case sInput
    Case "q"
      mPlayer.Stop()
      Quit
    Case "p"
      mPlayer.Pause()
    Case "r" ' Run
      mPlayer.Play()
    Case "m" ' Toggle switch: mute on/mute off
      mPlayer.Audio.Mute = Not mPlayer.Audio.Mute
    Case "+"
      If mPlayer.Audio.Volume > 0.09 And mPlayer.Audio.Volume < 9.0 Then
         mPlayer.Audio.Volume += fDeltaVolume
      Endif
    Case "-"
      If mPlayer.Audio.Volume > 0.2 And mPlayer.Audio.Volume < 10.0 Then
         mPlayer.Audio.Volume -= fDeltaVolume
      Endif
  End Select
 
End

Comment:

  • First, it checks whether an instance of the player already exists. If this is the case, the existing player object is destroyed and then a new player is started.
  • After starting with a given volume, 'Print #File.Out, TestString' prints instructions line by line in the console.
  • After that you can control the player by entering +, -, p, r, m and q (each followed by Enter).
  • The inputs are read from standard input with 'Line Input #File.In, sInput' and evaluated in a select-case control structure.

Download

Project

Download

The website uses a temporary session cookie. This technically necessary cookie is deleted when the browser is closed. You can find information on cookies in our privacy policy.
k6/k6.5/start.txt · Last modified: 16.01.2022 (external edit)

Page Tools