qb64

Conflicting FIELD statements in QB64


When running this code it seems testfile.000 contains "00" and testfile.001 contains "99", so, why is there no conflict between these files?? Should it throw a "duplicate definition."?

file1$ = "testfile.000"
file2$ = "testfile.001"
OPEN file1$ FOR RANDOM AS #1 LEN = 2
FIELD #1, 2 AS x$
OPEN file2$ FOR RANDOM AS #2 LEN = 2
FIELD #2, 2 AS x$
LSET x$ = "99"
PUT 1, 1
PUT 2, 1
END

Solution

  • In your code the second FIELD declaration overrides the first FIELD declaration. In BASIC the variables declared in the FIELD statement shall be different.

    If you use the code below, you can see an interesting result:

    The file testfile.000 will contain 1212 (only the first LSET set the field x$ of the file #1)

    The file testfile.001 will contain 1488 (both the LSET set the field x$ of the file #2).

    file1$ = "testfile.000"
    file2$ = "testfile.001"
    OPEN file1$ FOR RANDOM AS #1 LEN = 2
    FIELD #1, 2 AS x$
    LSET x$ = "12"
    
    OPEN file2$ FOR RANDOM AS #2 LEN = 2
    FIELD #2, 2 AS x$
    LSET x$ = "14"
    
    PUT #1, 1: REM This puts 12 into the 1st file#1 record.
    PUT #2, 1
    
    LSET x$ = "88"
    PUT #1, 2: REM this puts 12 into the 2nd file#1 record
    PUT #2, 2
    
    CLOSE #1
    CLOSE #2
    END
    

    In QB you may use binary files as in the code below. This mode allows you to write the same variable on more than one file.

    When you use this kind of files you will have full control of dimension and position of data into a file.

    file1$ = "testfile.000"
    file2$ = "testfile.001"
    OPEN file1$ FOR BINARY AS #1
    OPEN file2$ FOR BINARY AS #2
    
    x$ = "29"
    PUT #1, 1, x$
    PUT #2, 1, x$
    
    CLOSE #1
    CLOSE #2
    END