首页 > 解决方案 > 编写 COBOL 程序来反转记录并从一个文件移动到另一个文件的逻辑是什么?

问题描述

例如:

文件 1

AAA
BBB
CCC
DDD

文件2

DDD
CCC
BBB
AAA

标签: cobolmainframe

解决方案


编写 COBOL 程序来反转记录并从一个文件移动到另一个文件的逻辑是什么?

针对仅 COBOL 的解决方案,用于反转文件中记录序列的方法在 COBOL 85 和 COBOL 2002 之间发生了变化。具体而言,该REVERSED短语在 COBOL 85 中已过时,并在 COBOL 2002 中删除。


COBOL 85

以下要求输入是固定长度的记录ORGANIZATION SEQUENTIAL

代码:

   environment division.
   input-output section.
   file-control.
       select file1 assign "file1.dat"
           organization sequential
       .
       select file2 assign "file2.dat"
           organization sequential
       .
   data division.
   file section.
   fd file1.
   01 file1-rec pic x(4).
   fd file2.
   01 file2-rec pic x(4).
   working-storage section.
   01 eof-flag pic 9 value 0.
     88 eof-file1 value 1.
   procedure division.
   begin.
       open input file1 reversed
           output file2
       perform read-file1
       perform until eof-file1
           write file2-rec from file1-rec
           perform read-file1
       end-perform
       close file1 file2
       stop run
       .

   read-file1.
       read file1
       at end
           set eof-file1 to true
       end-read
       .

输入:

AAAABBBBCCCCDDDD

输出:

DDDDCCCCBBBBAAAA

[请注意,因为这些是固定长度的四字符记录,所以没有分隔符,因此,记录不会显示在单独的行中。]

对于RELATIVEorINDEXED文件,首先需要将记录复制到一个固定长度的顺序文件中,然后使用上述逻辑创建“反转”的顺序文件。对于变长记录,在使用上述反转之前,还需要将记录长度保存为定长记录的一部分。然后,与其编写固定长度的记录,不如编写可变长度的记录。


COBOL 2002(未经测试)

代码:

   environment division.
   input-output section.
   file-control.
       select file1 assign "file1.dat"
           organization sequential
       .
       select file2 assign "file2.dat"
           organization sequential
       .
   data division.
   file section.
   fd file1.
   01 file1-rec pic x(4).
   fd file2.
   01 file2-rec pic x(4).
   working-storage section.
   01 eof-flag pic 9 value 0.
     88 eof-file1 value 1.
   procedure division.
   begin.
       open input file1
           output file2
       start file1 last
       invalid key
           set eof-file1 to true
       not invalid key
           perform read-file1
       end-start
       perform until eof-file1
           write file2-rec from file1-rec
           perform read-file1
       end-perform
       close file1 file2
       stop run
       .

   read-file1.
       read file1 previous
       at end
           set eof-file1 to true
       end-read
       .

输入文件可能是SEQUENTIALRELATIVEINDEXED. 如果INDEXED,将使用主键。ACCESS必须是SEQUENTIALDYNAMIC。记录可以是固定长度或可变长度。

COBOL 2002 标准

START 语句 14.8.37.3 一般规则

顺序文件

21) 如果指定了LAST,则文件位置指示符设置为物理文件中最后一个现有逻辑记录的记录号。如果文件中不存在记录,或者物理文件不支持定位到最后一条记录的能力,则 file-name-1 引用的文件连接器中的 IO 状态值设置为 '23',无效键条件存在,并且 START 语句的执行不成功。

上面的代码,将无效的关键条件视为文件结束。


推荐阅读