Search code examples
cobol

COBOL reading sequential line file, count characters


in COBOL I am reading from sequential line file. Line by line, to EOF, something like that

           read bank-file  at end
            move 'Y'  to end-of-bank

And lines have variable length from 40 to 80 characters. And I need to know, how many characters are on each line. But line can end with some spaces, which I need count too. So I can't take length of string from variable in program. Is there any return value from READ statement, which returns number of characters from readed line (until, CRLF is reached)?


Solution

  • Edit

    As mentioned in the comments, it actually is possible to get the number of characters (bytes) read, indeed with the RECORD VARYING DEPENDING ON clause:

    ENVIRONMENT DIVISION.
    INPUT-OUTPUT SECTION.
    FILE-CONTROL.
    
        SELECT SOME-FILE
            ASSIGN TO "someFile.txt"
            ORGANIZATION IS LINE SEQUENTIAL.
    
    DATA DIVISION.
    FILE SECTION.
    
    FD SOME-FILE
        RECORD VARYING 40 TO 80 DEPENDING ON SOME-LINE-LENGTH.
    
     01 SOME-LINE PIC X(80).
    
    WORKING-STORAGE SECTION.
    
     77 SOME-LINE-LENGTH PIC 9(3).
    

    Now for each read, the record length is stored into SOME-LINE-LENGTH:

    READ SOME-FILE NEXT RECORD
    DISPLAY SOME-LINE-LENGTH
    

    I don't know exactly which vendors support it (possibly almost all), but at least it works with ACUCOBOL.


    Original post

    As far as I know, there is no feedback on the number of bytes read by the execution of the READ statement. Apparently, bytes are instantly stored into a record described by a file descriptor in your FILE SECTION.

    However, you can calculate the number of bytes read by counting the number of characters written to the record.
    First, initialize the file record to LOW-VALUES. Then read the next record; that will move the number of bytes read to the record. When the number of bytes read is smaller than the record size, the bytes at the end of the record are left unchanged.

    MOVE LOW-VALUES TO YOUR-RECORD
    READ YOUR-FILE NEXT RECORD
    PERFORM VARYING SOME-COUNTER FROM 72 BY -1 UNTIL (SOME-COUNTER < 0)
        IF NOT (YOUR-RECORD(SOME-COUNTER : 1) = LOW-VALUES)
            EXIT PERFORM
        END-IF
    END-PERFORM
    

    SOME-COUNTER will contain the line length, assuming no NUL values are present in the file.

    I guess this will be time-consuming when the number of lines is large, but at least you got your line lengths.


    As Bill Woodger already mentioned, since you didn't provide additional details, I had to make some assumptions.

    I'm running MicroFocus ACUCOBOL-GT on Windows 10 myself.