Difference between revisions of "OPEN"

From QB64 Wiki
Jump to navigation Jump to search
imported>Clippy
m
 
(23 intermediate revisions by 2 users not shown)
Line 1: Line 1:
The '''OPEN''' statement is used to open a file or [[OPEN_COM|COM]] serial communications port.
+
The [[OPEN]] statement is used to open a file or [[OPEN_COM|COM]] serial communications port for program input or output.
  
  
''Qbasic:'' {{PageSyntax}}
+
{{PageSyntax}}
 +
: [[OPEN]] {{Parameter|fileName$}} ['''FOR''' {{Parameter|mode}}] [{{{KW|ACCESS}}|{{{KW|LOCK}}|SHARED}} [{READ|WRITE}] [[AS]] [#]{{Parameter|fileNumber&}} [LEN = {{Parameter|recordLength}}]
  
::'''OPEN''' ''FileName$'' ['''FOR''' mode] [{{{KW|ACCESS}}|{{{KW|LOCK}}|SHARED}} [{READ|WRITE}] '''AS''' [#]''FileNumber&'' [LEN = ''recordLEN'']
 
  
 +
===Legacy ''GW-BASIC'' syntax===
 +
: [[OPEN]] {{Parameter|modeLetter$}}, [#]{{Parameter|fileNumber&}}, {{Parameter|fileName$}}[, {{Parameter|recordLength}}]
  
''Parameters:''
+
 
* ''FileName$'' is a [[STRING]] variable or literal file name in quotes.  
+
{{Parameters}}
* FOR mode can be: [[INPUT (file mode)|INPUT]] (read), [[OUTPUT]] (write new), [[APPEND]] (write to end), [[BINARY]] (read/write), [[RANDOM]] (read/write).
+
* The {{Parameter|fileName$}} is a [[STRING]] variable or literal file name (path optional) in quotes.  
* ''File number'' can be any '''positive''' [[INTEGER]] or [[LONG]] whole number value or an unused value determined by the [[FREEFILE]] function.
+
* FOR mode can be: [[APPEND]] (write to end), [[BINARY]] (read/write), [[INPUT (file mode)|INPUT]] (read), [[OUTPUT]] (write new) or [[RANDOM]] (read/write).
* [[LEN]] = is optional to denote RANDOM record length.  LEN = statement is ignored in [[BINARY]] mode.
+
* GW-BASIC's {{Parameter|modeLetter$}} is a [[STRING]] variable or the letter "A", "B", "I", "O" or "R" designating the OPEN modes above.
 +
* {{Parameter|fileNumber&}} can be any '''positive''' [[INTEGER]] or [[LONG]] whole number value or an unused value determined by the [[FREEFILE]] function.
 +
* [[LEN]] = or {{Parameter|recordLength}} is optional to denote the RANDOM file record byte length (default = 128) or sequential (default = 512) load buffer.
  
  
 
{{PageDescription}}
 
{{PageDescription}}
* '''QB64''' can open as many files as your computer memory can handle. Qbasic could only open about 15 at a time.
+
* '''QB64''' can open as many files as your computer memory can handle. QBasic could only open about 15 at a time.
 
* '''QB64 will allocate 4 bytes of memory for every possible file number up to the highest number used in a program.'''
 
* '''QB64 will allocate 4 bytes of memory for every possible file number up to the highest number used in a program.'''
* The ''mode'' defaults to RANDOM if the ''mode'' or FOR access statement is omitted. (see open modes described below)
+
* {{Parameter|mode}} defaults to RANDOM if the {{Parameter|mode}} or FOR access statement is omitted. (see open modes described below)
* '''Only the ''filename'', ''file number'' and LEN = ''record length'' values can use variable values in the Qbasic OPEN syntax.'''
+
* '''Only the {{Parameter|fileName$}}, {{Parameter|fileNumber&}} and LEN = {{Parameter|recordLength}} values can use variable values in the QBasic syntax.'''
 
* If [[LEN]] = is ommitted, sequential file record sizes default to 512 and [[RANDOM]] to 128 bytes in Qbasic.
 
* If [[LEN]] = is ommitted, sequential file record sizes default to 512 and [[RANDOM]] to 128 bytes in Qbasic.
* '''QB64''' ''filenames'' can be up to 255(Windows) characters with no limit on file name extension length.  
+
* {{Parameter|fileName$}} can be up to 255 characters with no limit on file name extension length in '''QB64'''.  
 
* Once a file or port is opened, it can be used in any program procedure using the assigned file number.  
 
* Once a file or port is opened, it can be used in any program procedure using the assigned file number.  
* The '''"SCRN:"''' device is now supported in all new GL versions after April 15, 2015(see Example 3).
+
* The '''"SCRN:"''' device is supported in '''version 1.000 and up''' (see Example 3).
* '''Devices such as "KYBD:", "CONS:", "COMn" and "LPTn:" are [[Keywords currently not supported by QB64|currently NOT supported in QB64!]]'''.  
+
* '''Devices such as "KYBD:", "CONS:", "COMn" and "LPTn:" are [[Keywords currently not supported by QB64|not supported in QB64.]]'''.  
 
: '''Note:''' OPEN "LPTn" is not supported by QB64, but may be supported directly by your operating system.  
 
: '''Note:''' OPEN "LPTn" is not supported by QB64, but may be supported directly by your operating system.  
 
* [[OPEN COM]] can also be used for serial port access in '''QB64'''.
 
* [[OPEN COM]] can also be used for serial port access in '''QB64'''.
Line 29: Line 33:
  
 
{{PageErrors}}
 
{{PageErrors}}
* Illegal Qbasic filename characters are ''' " * / \ + | ? [ ] , ; : < > ''' and more than one dot(period).
+
* Illegal '''QB64''' Windows filename characters are ''' " * / \ | ? : < > '''. Multiple dots (periods) are allowed.
* Illegal '''QB64''' filename characters are ''' " * / \ | ? : < > '''. Multiple dots(periods) are allowed, but only the first one will be used.
 
* Qbasic ''filenames'' must not exceed 12 characters(including dot) with a maximum of 3 file type extension characters using the DOS 8.3 naming convention limits.
 
 
* Possible OPEN [[ERROR Codes|errors]] include "Bad file name or number", "Bad File Mode", "File Not Found" or "Path Not Found".
 
* Possible OPEN [[ERROR Codes|errors]] include "Bad file name or number", "Bad File Mode", "File Not Found" or "Path Not Found".
 +
** An OPEN file not found error may occur if [[CHR$]](0) to (31) are used in a Windows file name.
 +
* '''QB64''' does not have DOS file name limitations.
  
  
<center> ''' File ACCESS and LOCK Permissions'''</center>
+
==Details==
 
+
===File ACCESS and LOCK Permissions===
* [[ACCESS]] clause limits file access to READ, WRITE or READ WRITE on a network ONLY with DOS 3.1 or greater.
+
* [[ACCESS]] clause limits file access to READ, WRITE or READ WRITE on a network.
 
* [[LOCK (access)|LOCK]] clause can specify SHARED or a LOCK READ or LOCK WRITE file lock in an OPEN statement working on a network.
 
* [[LOCK (access)|LOCK]] clause can specify SHARED or a LOCK READ or LOCK WRITE file lock in an OPEN statement working on a network.
* A separate [[LOCK]] statement can lock or [[UNLOCK]] file access on a network ONLY using a format that can lock specific records.
+
* A separate [[LOCK]] statement can lock or [[UNLOCK]] file access on a network using a format that can lock specific records.
* ''Note:'' '''Qbasic''' ACCESS and LOCK clauses required that the DOS '''SHARED.EXE''' program be run for networking access.
+
* If another process already has access to a specified file, program access is denied for that file OPEN access. A "Permission Denied" error 70 will be returned. A network program must be able to handle a denial of access error.
 
 
 
 
<center>'''The 5 Qbasic File Access Modes:'''</center>
 
 
 
* [[OUTPUT]]: Sequencial mode creates a new file or erases an existing file for new program output. Use [[WRITE (file statement)|WRITE #]] to write numerical or text data or the [[PRINT (file statement)|PRINT #]] for text. OUTPUT clears files of all data and clears the receive buffer on other devices such as [[ON COM(n)|COM]].
 
* [[APPEND]]: Sequencial mode creates a new file if it doesn't exist or appends program output to an existing file. Use [[WRITE (file statement)|WRITE #]] for numerical or text data or the [[PRINT (file statement)|PRINT #]] for text as in the OUTPUT mode. APPEND does not remove previous data.
 
* [[BINARY]]: Creates a new file when it doesn't exist or uses input and/or output from an existing binary file. Use [[GET|GET #]] to read or [[PUT|PUT #]] to write byte positions simultaneously. [[LEN]] = statements are ignored in this mode only.
 
* [[RANDOM]]: Creates a new file when it doesn't exist or uses input and/or output from an existing file. Use [[GET|GET #]] or [[PUT|PUT #]] to read or write to file records. A [[LEN]] = statement can define the byte size of a record(no LEN statement defaults to 128 bytes).
 
* [[INPUT (file mode)|INPUT]] : Sequencial mode only reads input from an existing file. [[ERROR Codes|File error]] if file does not exist! Use [[_FILEEXISTS]] and [[_DIREXISTS]] to avoid errors. Use [[INPUT (file statement)|INPUT #]] for numerical or text data and [[LINE INPUT (file statement)|LINE INPUT #]] or [[INPUT$]] to only read text data.
 
* The [[INPUT (file mode)|INPUT]], [[BINARY]] and [[RANDOM]] file modes allow a file to be concurrently opened in a different mode and number.
 
 
 
 
 
<center>'''GW Basic OPEN statements'''</center>
 
 
 
 
 
:''GW Basic'' {{PageSyntax}}
 
::'''OPEN''' ''modeletter$'', [#]''filenumber'', ''filename$''[, ''recordLEN'']
 
 
 
 
 
:* ''Mode letter'' is a variable or literal [[STRING]] letter value as one of the following:
 
 
 
::* "A" [[APPEND]] sequential mode allows data to be appended to an existing file using [[PRINT (file statement)|PRINT]] or [[WRITE (file statement)|WRITE]].
 
::* "B" [[BINARY]] byte mode allows data to be read or written using [[GET]] or [[PUT]]
 
::* "I" [[INPUT (file mode)|INPUT]] sequential mode allows data to be read using [[INPUT (file statement)|INPUT]] or [[LINE INPUT (file statement)|LINE INPUT]] in '''existing''' files only.
 
::* "O" [[OUTPUT]] sequential mode creates or clears a file to write new data using [[PRINT (file statement)|PRINT]] or [[WRITE (file statement)|WRITE]].
 
::* "R" [[RANDOM]] record mode allows [[TYPE]] or [[FIELD]] records to be read or written using [[GET]] or [[PUT]].
 
 
 
 
 
:* ''File number'' can be any variable or literal [[INTEGER]] value between 1 and 255 or a  [[FREEFILE]] value.
 
:* ''File name'' can be a variable or literal [[STRING]] file name value or port or device.
 
:* '''Devices such as "KYBD:", "SCRN:", "CONS:", "COMn" and "LPTn:" as file names are [[Keywords currently not supported by QB64|currently NOT supported in QB64!]]'''.
 
:: '''Note:''' OPEN "O", #1, "LPTn" is not supported by QB64, but may be supported directly by your operating system.
 
:* ''RecordLEN'' can be a variable or literal [[INTEGER]] value used in "R" mode only.
 
:* This type of OPEN allows the statement to be made using program variables only. A holdover for compatibility with GW Basic.
 
:* '''Note:''' Does not support any file [[ACCESS]] or [[LOCK]] restrictions.
 
 
 
 
 
<center> '''Comparing the GWBasic OPEN to a Qbasic OPEN statement:'''</center>
 
  
 +
===File Access Modes===
 +
* FOR mode can be:
 +
** '''OUTPUT''': Sequential mode creates a new file or erases an existing file for new program output. Use [[WRITE (file statement)|WRITE #]] to write numerical or text data or [[PRINT (file statement)|PRINT #]] for text. '''OUTPUT clears files of all data''' and clears the receive buffer on other devices such as [[ON COM(n)|COM]].
 +
** '''APPEND''': Sequential mode creates a new file if it doesn't exist or appends program output to the end of an existing file. Use [[WRITE (file statement)|WRITE #]] for numerical or text data or [[PRINT (file statement)|PRINT #]] for text as in the OUTPUT mode. '''APPEND does not remove previous data.'''
 +
** '''INPUT''' : Sequential mode '''only reads input''' from an existing file. '''[[ERROR Codes|File error]] if file does not exist.''' Use [[INPUT (file statement)|INPUT #]] for comma separated numerical or text data and [[LINE INPUT (file statement)|LINE INPUT #]] or [[INPUT$]] to only read text data. '''Use [[_FILEEXISTS]] or [[_DIREXISTS]] to avoid errors.'''
 +
** '''BINARY''': Creates a new file when it doesn't exist or reads and writes to an existing binary file. Use [[GET|GET #]] to read or [[PUT|PUT #]] to write byte positions simultaneously. [[LEN]] = statements are ignored in this mode.
 +
** '''RANDOM''': Creates a new file when it doesn't exist or reads or writes to an existing random file record. Use [[GET|GET #]] or [[PUT|PUT #]] to read or write to file records. A [[LEN]] = statement can define the byte size of a record (no LEN statement defaults to 128 bytes)
 +
** Modes '''INPUT''', '''BINARY''' and '''RANDOM''' allow a file to be concurrently opened in a different mode and number.
  
::::::::::GWBasic: OPEN "A", #1, Filename$
 
  
::::::::::Qbasic: OPEN Filename$ FOR APPEND AS #1
+
====GW-BASIC modes====
 +
* ''Mode letter'' is a variable or literal [[STRING]] letter value as one of the following:
 +
** "A" = '''APPEND'''.
 +
** "B" = '''BINARY'''.
 +
** "I" = '''INPUT'''.
 +
** "O" = '''OUTPUT'''.
 +
** "R" = '''RANDOM'''.
  
:Where Filename$ is the filename variable or a literal string name such as "Data1.DAT" is used. The Qbasic syntax cannot use a variable to change the OPEN mode so the programmer must determine it ahead of time.
 
  
 
+
{{PageExamples}}
 
+
''Example 1:'' Function that displays errors and the number of errors in QBasic filenames. Returns 0 when filename is OK.
''Example 1:'' Function that displays errors and the number of errors in Qbasic filenames. Returns 0 when filename is OK.
 
  
 
{{CodeStart}}
 
{{CodeStart}}
 
  file$ = "Hello,~1.mp3"      'example call below
 
  file$ = "Hello,~1.mp3"      'example call below
  LOCATE 20, 30: errors% = CheckName%(file$): COLOR 14: PRINT "  Total Errors ="; errors%  
+
  {{Cl|LOCATE}} 20, 30: errors% = CheckName%(file$): {{Cl|COLOR}} 14: {{Cl|PRINT}} "  Total Errors ="; errors%  
  
 
{{Cl|FUNCTION}} CheckName% (Filename$)
 
{{Cl|FUNCTION}} CheckName% (Filename$)
   'NOTE: Function also displays filename errors so LOCATE on screen before call!
+
   '{{Cl|NOT}}E: Function also displays filename errors so {{Cl|LOCATE}} on screen before call!
   {{Cl|DIM}} L AS INTEGER, DP AS INTEGER, XL AS {{Cl|INTEGER}}
+
   {{Cl|DIM}} L {{Cl|AS}} {{Cl|INTEGER}}, DP {{Cl|AS}} {{Cl|INTEGER}}, XL {{Cl|AS}} {{Cl|INTEGER}}
   L = {{Cl|LEN}}(Filename$): DP = {{Cl|INSTR}}(Filename$, "."): IF DP THEN XL = L - DP 'extension
+
   L = {{Cl|LEN}}(Filename$): DP = {{Cl|INSTR}}(Filename$, "."): {{Cl|IF...THEN|IF}} DP {{Cl|THEN}} XL = L - DP 'extension
   IF L = 0 OR L > 12 OR DP > 9 OR XL > 3 THEN  
+
   {{Cl|IF...THEN|IF}} L = 0 {{Cl|OR (boolean)|OR}} L > 12 {{Cl|OR (boolean)|OR}} DP > 9 {{Cl|OR (boolean)|OR}} XL > 3 {{Cl|THEN}}
     CheckName% = -1: COLOR 12: PRINT "Illegal format!"; : EXIT FUNCTION
+
     CheckName% = -1: {{Cl|COLOR}} 12: {{Cl|PRINT}} "Illegal format!"; : {{Cl|EXIT FUNCTION}}
   END IF
+
   {{Cl|END IF}}
   FOR i% = 1 TO L      'check each filename character"
+
   {{Cl|FOR...NEXT|FOR}} i% = 1 {{Cl|TO}} L      'check each filename character"
     code% = {{Cl|ASC}}({{Cl|MID$}}(Filename$, i%, 1)): COLOR 10      ' see {{Cl|ASCII}} codes
+
     code% = {{Cl|ASC}}({{Cl|MID$}}(Filename$, i%, 1)): {{Cl|COLOR}} 10      ' see ASCII codes
 
     {{Cl|SELECT CASE}} code%      'check for errors and highlight in red
 
     {{Cl|SELECT CASE}} code%      'check for errors and highlight in red
CASE 34, 42 TO 44, 47, 58 TO 63, 91 TO 93, 124: E% = E% + 1: COLOR 12 ' Qbasic errors
+
'{{Cl|CASE}} 34, 42 {{Cl|TO}} 44, 47, 58 {{Cl|TO}} 63, 91 {{Cl|TO}} 93, 124: E% = E% + 1: {{Cl|COLOR}} 12 ' '''QBasic errors'''
      'CASE 34, 42, 47, 58, 60, 62, 92, 124: E% = E% + 1: COLOR 12 ' '''QB64''' errors
+
        {{Cl|CASE}} 34, 42, 47, 58, 60, 62, 92, 124: E% = E% + 1: {{Cl|COLOR}} 12 ' '''QB64 errors'''
         CASE 46: dot% = dot% + 1: IF dot% > 1 THEN E% = E% + 1: COLOR 12
+
         {{Cl|CASE}} 46: dot% = dot% + 1: {{Cl|IF...THEN|IF}} dot% > 1 {{Cl|THEN}} E% = E% + 1: {{Cl|COLOR}} 12
 
     {{Cl|END SELECT}}     
 
     {{Cl|END SELECT}}     
     PRINT {{Cl|CHR$}}(code%);  'use LOCATE before FUNCTION call to place print
+
     {{Cl|PRINT}} {{Cl|CHR$}}(code%);  'use {{Cl|LOCATE}} before {{Cl|FUNCTION}} call to place print
   NEXT   
+
   {{Cl|NEXT}}  
 
   CheckName% = E%
 
   CheckName% = E%
END FUNCTION
+
{{Cl|END FUNCTION}} '' ''
 
{{CodeEnd}}
 
{{CodeEnd}}
''Note: The QB64 character list is commented out. Comment out the Qbasic one if using QB64 list.
+
''Note: The QBasic character error list is commented out and the function will return invalid filenames under QB64.
  
 
{{OutputStart}}
 
{{OutputStart}}
                         Hello,~1.mp3  Total Errors = 1
+
                         {{text|Hello|#54FC54}}{{text|,|red}}{{text|~1.mp3|#54FC54}} {{text|Total Errors|yellow}}<nowiki> = </nowiki>{{text|1|yellow}}
 
{{OutputEnd}}
 
{{OutputEnd}}
:''Note:'' The screen output displays filename characters in green except for red comma Qbasic error.
+
:''Note:'' The screen output displays filename characters in green except for red comma QBasic error.
  
  
''Example 2:'' A function that verifies that a file exists if it is NOT empty. Note: May create a file that is deleted if empty.
+
''Example 2:'' When '''OPEN "SCRN:" FOR OUTPUT AS #f''' is used, '''PRINT #f''' will print the text to the screen instead of to a file:
{{CodeStart}} '' ''
 
{{Cl|INPUT}} "Enter a file name: ", file$
 
{{Cl|IF}} Exist%(file$) {{Cl|THEN}} {{Cl|OPEN}} file$ {{Cl|FOR (file statement)|FOR}} {{Cl|INPUT (file mode)|INPUT}} {{Cl|AS}} #1: found% = -1  'function call demo
 
{{Cl|CLOSE}} #1
 
{{Cl|IF}} found% THEN {{Cl|PRINT}} "File exists!" {{Cl|ELSE}} {{Cl|PRINT}} "File not found!"
 
{{Cl|END}}
 
 
 
{{Cl|FUNCTION}} Exist% (filename$)
 
f% = {{Cl|FREEFILE}}
 
{{Cl|OPEN}} filename$ {{Cl|FOR (file statement)|FOR}} {{Cl|APPEND}} {{Cl|AS}} #f%
 
{{Cl|IF}} {{Cl|LOF}}(f%) {{Cl|THEN}} Exist% = -1 {{Cl|ELSE}} Exist% = 0: {{Cl|CLOSE}} #f%: {{Cl|KILL}} filename$
 
{{Cl|CLOSE}} #f%
 
{{Cl|END FUNCTION}} '' ''
 
{{CodeEnd}}
 
{{small|Code by Ted Weissgerber}}
 
 
 
 
 
''Example 3:'' When '''OPEN "SCRN:" FOR OUTPUT AS #f''' is used, '''PRINT #f''' will print the text to the screen instead of to a file:
 
 
{{CodeStart}} '' ''
 
{{CodeStart}} '' ''
 
f% = {{Cl|FREEFILE}} 'should always be 1 at program start
 
f% = {{Cl|FREEFILE}} 'should always be 1 at program start
Line 150: Line 109:
 
     {{Cl|PRINT (file statement)|PRINT}} #i, "Hello World, Screen and File version"
 
     {{Cl|PRINT (file statement)|PRINT}} #i, "Hello World, Screen and File version"
 
NEXT '' ''
 
NEXT '' ''
{{CodeEnd}}{{small|GL implementation by Steve McNeill April 15, 2015}}
+
{{CodeEnd}}{{small|code by Steve McNeill}}
: ''Note:'' Even an OPEN to "SCRN:" instead of a file will cause the next FREEFILE number to change.  
+
: ''Note:'' Linux or Mac file names can use a path destination such as ".\SCRN:" to use SCRN: as an actual file name.  
  
  
* '''QB64''' can use the [[_OPENCLIENT]], [[_OPENHOST]] or [[_OPENCONNECTION]] functions for TCP/IP internet connections.  
+
''Example 3:'' Showcasing different file modes.
 +
{{CodeStart}}
 +
{{Cl|CLS}}
  
 +
{{Cl|OPEN}} "test.tst" {{Cl|FOR (file statement)|FOR}} {{Cl|OUTPUT}} {{Cl|AS}} #1
 +
{{Cl|PRINT (file statement)|PRINT}} #1, "If test.tst didn't exist:"
 +
{{Cl|PRINT (file statement)|PRINT}} #1, "A new file was created named test.tst and then deleted."
 +
{{Cl|PRINT (file statement)|PRINT}} #1, "If test.tst did exist:"
 +
{{Cl|PRINT (file statement)|PRINT}} #1, "It was overwritten with this and deleted."
 +
{{Cl|CLOSE}} #1
 +
 +
{{Cl|OPEN}} "test.tst" {{Cl|FOR (file statement)|FOR}} {{Cl|INPUT (file mode)|INPUT}} {{Cl|AS}} #1
 +
{{Cl|DO}} {{Cl|UNTIL}} {{Cl|EOF}}(1)
 +
{{Cl|INPUT (file statement)|INPUT}} #1, a$
 +
{{Cl|PRINT}} a$
 +
{{Cl|LOOP}}
 +
{{Cl|CLOSE}} #1
 +
 +
{{Cl|KILL}} "test.tst"
 +
 +
{{Cl|END}}
 +
 +
{{CodeEnd}}
 +
 +
{{OutputStart}}
 +
If test.tst didn't exist:
 +
A new file was created named test.tst and then deleted.
 +
If test.tst did exist:
 +
It was overwritten with this and deleted.
 +
{{OutputEnd}}
 +
:'''Warning:''' Make sure you don't have a file named test.tst before you run this or it will be overwritten.
  
  
''See also:''
+
{{PageSeeAlso}}
 
* [[PRINT (file statement)]], [[INPUT (file statement)]]
 
* [[PRINT (file statement)]], [[INPUT (file statement)]]
 
* [[GET]], [[PUT]], [[WRITE (file statement)]]  
 
* [[GET]], [[PUT]], [[WRITE (file statement)]]  
Line 165: Line 153:
 
* [[SEEK (statement)]], [[SEEK]]
 
* [[SEEK (statement)]], [[SEEK]]
 
* [[OPEN COM]], [[LEN]], [[RESET]]  
 
* [[OPEN COM]], [[LEN]], [[RESET]]  
* [[FILEATTR]], [[FIELD]], [[TYPE]]
+
* [[FIELD]], [[TYPE]]
 
* [[_FILEEXISTS]], [[_DIREXISTS]]
 
* [[_FILEEXISTS]], [[_DIREXISTS]]
 
* [[_OPENCLIENT]], [[_OPENHOST]], [[_OPENCONNECTION]] {{text|(TCP/IP)}}
 
* [[_OPENCLIENT]], [[_OPENHOST]], [[_OPENCONNECTION]] {{text|(TCP/IP)}}
 
* [[_SNDOPEN]], [[_LOADIMAGE]]
 
* [[_SNDOPEN]], [[_LOADIMAGE]]
* [[Port Access Libraries]] {{text|(COM or LPT registers)}}
 
  
  
 
{{PageNavigation}}
 
{{PageNavigation}}

Latest revision as of 23:47, 30 July 2020

The OPEN statement is used to open a file or COM serial communications port for program input or output.


Syntax

OPEN fileName$ [FOR mode] [{ACCESS|{LOCK|SHARED}} [{READ|WRITE}] AS [#]fileNumber& [LEN = recordLength]


Legacy GW-BASIC syntax

OPEN modeLetter$, [#]fileNumber&, fileName$[, recordLength]


Parameters

  • The fileName$ is a STRING variable or literal file name (path optional) in quotes.
  • FOR mode can be: APPEND (write to end), BINARY (read/write), INPUT (read), OUTPUT (write new) or RANDOM (read/write).
  • GW-BASIC's modeLetter$ is a STRING variable or the letter "A", "B", "I", "O" or "R" designating the OPEN modes above.
  • fileNumber& can be any positive INTEGER or LONG whole number value or an unused value determined by the FREEFILE function.
  • LEN = or recordLength is optional to denote the RANDOM file record byte length (default = 128) or sequential (default = 512) load buffer.


Description

  • QB64 can open as many files as your computer memory can handle. QBasic could only open about 15 at a time.
  • QB64 will allocate 4 bytes of memory for every possible file number up to the highest number used in a program.
  • mode defaults to RANDOM if the mode or FOR access statement is omitted. (see open modes described below)
  • Only the fileName$, fileNumber& and LEN = recordLength values can use variable values in the QBasic syntax.
  • If LEN = is ommitted, sequential file record sizes default to 512 and RANDOM to 128 bytes in Qbasic.
  • fileName$ can be up to 255 characters with no limit on file name extension length in QB64.
  • Once a file or port is opened, it can be used in any program procedure using the assigned file number.
  • The "SCRN:" device is supported in version 1.000 and up (see Example 3).
  • Devices such as "KYBD:", "CONS:", "COMn" and "LPTn:" are not supported in QB64..
Note: OPEN "LPTn" is not supported by QB64, but may be supported directly by your operating system.
  • OPEN COM can also be used for serial port access in QB64.


Errors

  • Illegal QB64 Windows filename characters are " * / \ | ? : < > . Multiple dots (periods) are allowed.
  • Possible OPEN errors include "Bad file name or number", "Bad File Mode", "File Not Found" or "Path Not Found".
    • An OPEN file not found error may occur if CHR$(0) to (31) are used in a Windows file name.
  • QB64 does not have DOS file name limitations.


Details

File ACCESS and LOCK Permissions

  • ACCESS clause limits file access to READ, WRITE or READ WRITE on a network.
  • LOCK clause can specify SHARED or a LOCK READ or LOCK WRITE file lock in an OPEN statement working on a network.
  • A separate LOCK statement can lock or UNLOCK file access on a network using a format that can lock specific records.
  • If another process already has access to a specified file, program access is denied for that file OPEN access. A "Permission Denied" error 70 will be returned. A network program must be able to handle a denial of access error.

File Access Modes

  • FOR mode can be:
    • OUTPUT: Sequential mode creates a new file or erases an existing file for new program output. Use WRITE # to write numerical or text data or PRINT # for text. OUTPUT clears files of all data and clears the receive buffer on other devices such as COM.
    • APPEND: Sequential mode creates a new file if it doesn't exist or appends program output to the end of an existing file. Use WRITE # for numerical or text data or PRINT # for text as in the OUTPUT mode. APPEND does not remove previous data.
    • INPUT : Sequential mode only reads input from an existing file. File error if file does not exist. Use INPUT # for comma separated numerical or text data and LINE INPUT # or INPUT$ to only read text data. Use _FILEEXISTS or _DIREXISTS to avoid errors.
    • BINARY: Creates a new file when it doesn't exist or reads and writes to an existing binary file. Use GET # to read or PUT # to write byte positions simultaneously. LEN = statements are ignored in this mode.
    • RANDOM: Creates a new file when it doesn't exist or reads or writes to an existing random file record. Use GET # or PUT # to read or write to file records. A LEN = statement can define the byte size of a record (no LEN statement defaults to 128 bytes)
    • Modes INPUT, BINARY and RANDOM allow a file to be concurrently opened in a different mode and number.


GW-BASIC modes

  • Mode letter is a variable or literal STRING letter value as one of the following:
    • "A" = APPEND.
    • "B" = BINARY.
    • "I" = INPUT.
    • "O" = OUTPUT.
    • "R" = RANDOM.


Examples

Example 1: Function that displays errors and the number of errors in QBasic filenames. Returns 0 when filename is OK.

file$ = "Hello,~1.mp3" 'example call below LOCATE 20, 30: errors% = CheckName%(file$): COLOR 14: PRINT " Total Errors ="; errors% FUNCTION CheckName% (Filename$) 'NOTE: Function also displays filename errors so LOCATE on screen before call! DIM L AS INTEGER, DP AS INTEGER, XL AS INTEGER L = LEN(Filename$): DP = INSTR(Filename$, "."): IF DP THEN XL = L - DP 'extension IF L = 0 OR L > 12 OR DP > 9 OR XL > 3 THEN CheckName% = -1: COLOR 12: PRINT "Illegal format!"; : EXIT FUNCTION END IF FOR i% = 1 TO L 'check each filename character" code% = ASC(MID$(Filename$, i%, 1)): COLOR 10 ' see ASCII codes SELECT CASE code% 'check for errors and highlight in red 'CASE 34, 42 TO 44, 47, 58 TO 63, 91 TO 93, 124: E% = E% + 1: COLOR 12 ' QBasic errors CASE 34, 42, 47, 58, 60, 62, 92, 124: E% = E% + 1: COLOR 12 ' QB64 errors CASE 46: dot% = dot% + 1: IF dot% > 1 THEN E% = E% + 1: COLOR 12 END SELECT PRINT CHR$(code%); 'use LOCATE before FUNCTION call to place print NEXT CheckName% = E% END FUNCTION

Note: The QBasic character error list is commented out and the function will return invalid filenames under QB64.

Hello,~1.mp3 Total Errors = 1

Note: The screen output displays filename characters in green except for red comma QBasic error.


Example 2: When OPEN "SCRN:" FOR OUTPUT AS #f is used, PRINT #f will print the text to the screen instead of to a file:

f% = FREEFILE 'should always be 1 at program start OPEN "SCRN:" FOR OUTPUT AS #f% g% = FREEFILE 'should always be 2 after 1 OPEN "temp.txt" FOR OUTPUT AS #g% FOR i = 1 TO 2 PRINT #i, "Hello World, Screen and File version" NEXT

code by Steve McNeill
Note: Linux or Mac file names can use a path destination such as ".\SCRN:" to use SCRN: as an actual file name.


Example 3: Showcasing different file modes.

CLS OPEN "test.tst" FOR OUTPUT AS #1 PRINT #1, "If test.tst didn't exist:" PRINT #1, "A new file was created named test.tst and then deleted." PRINT #1, "If test.tst did exist:" PRINT #1, "It was overwritten with this and deleted." CLOSE #1 OPEN "test.tst" FOR INPUT AS #1 DO UNTIL EOF(1) INPUT #1, a$ PRINT a$ LOOP CLOSE #1 KILL "test.tst" END

If test.tst didn't exist: A new file was created named test.tst and then deleted. If test.tst did exist: It was overwritten with this and deleted.

Warning: Make sure you don't have a file named test.tst before you run this or it will be overwritten.


See also



Navigation:
Go to Keyword Reference - Alphabetical
Go to Keyword Reference - By usage
Go to Main WIKI Page