Working with Files – Part 3

Processing a Fixed-Width "COBOL-Style" File

 

Example – Reading a Fixed-Width "COBOL-Style" File:

 

Recall the fixed-width "COBOL-Style" format version of the employee file shown earlier:

 

            1    1    2    2   3    3    4    4    5    5    6    6

   1...5....0....5....0....5...0....5....0....5....0....5....0....5.   

ANDY ANDERSON       0100PROGRAMMER       030419972500

BILLY BABCOCK       0110SYSTEMS ANALYST  021619963350

CHARLIE CHEESEMAN   0100COMPUTER OPERATOR030119961500

DARLENE DUNCAN      0200RECEPTIONIST     101119981275

ERNIE EACHUS        0300MAIL ROOM CLERK  081919971000

 

The processing for this file is similar to the processing in the previous example.  The differences occur with the hire date and hourly rate fields.  With the date field, slashes must be inserted between the MM, DD, and YYYY components in order for the CDate function to return the proper result.  Concerning the hourly rate field, it must be divided by 100 to account for the "implied" decimal position.

 

A modified version of the previous example is shown below, with the new statements shown in bold:

 

  Dim strEmpFileName As String

  Dim strBackSlash   As String

  Dim intEmpFileNbr  As Integer

 

  Dim strEmpRecord   As String

  Dim strEmpName     As String

  Dim intDeptNbr     As Integer

  Dim strJobTitle    As String

  Dim strSlashDate   As String

  Dim dtmHireDate    As Date

  Dim sngHrlyRate    As Single

 

  strBackSlash = IIf (Right$(App.Path, 1) = "\", "", "\")

  strEmpFileName = App.Path & strBackSlash & "EMPLOYEE.DAT"

  intEmpFileNbr = FreeFile

 

  Open strEmpFileName For Input As #intEmpFileNbr

  Do Until EOF(intEmpFileNbr)

      Line Input #intEmpFileNbr, strEmpRecord  

      strEmpName = Left$(strEmpRecord, 20)

      intDeptNbr = Val(Mid$(strEmpRecord, 21, 4))

      strJobTitle = Mid$(strEmpRecord, 25, 17)

      strSlashDate = Mid$(strEmpRecord, 43, 2) & "/" _

                   & Mid$(strEmpRecord, 45, 2) & "/" _

                   & Mid$(strEmpRecord, 47, 4)

      dtmHireDate = CDate(strSlashDate)

      sngHrlyRate = Val(Mid$(strEmpRecord, 51, 4)) / 100

      Print strEmpName; _

            Tab(25); Format$(intDeptNbr, "@@@@"); _

            Tab(35); strJobTitle; _

            Tab(60); Format$(dtmHireDate, "mm/dd/yyyy"); _

            Tab(71); Format$(Format$(sngHrlyRate, "Standard"), "@@@@@@@")

  Loop

 

  Close #intEmpFileNbr

 

To demonstrate the code above

 

Download the VB project code for the example above here.