是否可以在COBOL程序中在运行时动态指定文件名?

时间:2017-10-12 08:04:29

标签: cobol

是否可以在COBOL程序中在运行时动态指定文件名?

例如,我想在编写File-Control部分时不必定义要打开的文件的名称,我想从不同的文件中读取要打开的文件的名称包含名称,我还想定义(FD)我将名称传递给File-COntrol时要打开的文件。

该平台是带有Micro Focus Visual Cobol编译器的Unix。

2 个答案:

答案 0 :(得分:1)

当人们寻求帮助时,发布了一段无需编译的代码片段,我真的很喜欢它。

IDENTIFICATION DIVISION.

PROGRAM-ID.     STACK-OVERFLOW-1.
AUTHOR.         Roland Hughes.
DATE-WRITTEN.   TODAY.
DATE-COMPILED.  TODAY.

ENVIRONMENT DIVISION.

INPUT-OUTPUT SECTION.

  FILE-CONTROL.
      SELECT OPTIONAL OUT_FILE
          ASSIGN TO DISK
          ORGANIZATION IS SEQUENTIAL
          ACCESS MODE IS SEQUENTIAL
          FILE STATUS IS IN-STAT.

DATA DIVISION.

FILE SECTION.
  FD OUT_FILE
     IS GLOBAL
     VALUE OF FILE-ID IS OUT_FILE_NAME
     LABEL RECORDS ARE STANDARD.

    01 DTL-LINE.
      03 FIELDA      PIC X(14).
      03 FIELDB      PIC X(10).
      03 FIELDC      PIC X(32).
      03 FIELDD      PIC X(03).
      03 FIELDE      PIC X(02).

WORKING-STORAGE SECTION.
    01 STATUS-VARIABLES.
       05 IN-STAT           PIC X(2).

    01 STUFF.
       05 OUT_FILE_NAME     PIC X(80).

PROCEDURE DIVISION. 
    MOVE "FILE1.DAT" to OUT_FILE_NAME.
    OPEN OUTPUT OUT_FILE.
    MOVE SPACES TO DTL-LINE.
    MOVE 'HELLO!' TO FIELDA.
    WRITE DTL-LINE.
    CLOSE OUT_FILE

    MOVE "FILE2.DAT" to OUT_FILE_NAME.
    OPEN OUTPUT OUT_FILE.
    MOVE SPACES TO DTL-LINE.
    MOVE 'HI!' TO FIELDB.
    WRITE DTL-LINE.
    CLOSE OUT_FILE.

    MOVE "FILE3.DAT" to OUT_FILE_NAME.
    OPEN OUTPUT OUT_FILE.
    MOVE SPACES TO DTL-LINE.
    MOVE 'FRED' TO FIELDC.
    WRITE DTL-LINE.
    CLOSE OUT_FILE.
STOP RUN.

我在KDE Neon上测试了此功能,并安装了所有最新更新。我从存储库中安装了open-cobol软件包。

cobc -x -free STACK-OVERFLOW-1.COB 
./STACK-OVERFLOW-1 

roland@roland-HP-EliteDesk-800-G2-SFF:~/COBOL$ ls *.DAT
FILE1.DAT  FILE2.DAT  FILE3.DAT
roland@roland-HP-EliteDesk-800-G2-SFF:~/COBOL$ cat *.DAT
HELLO!                                                                     HI!                                                                    FRED                                 roland@roland-HP-EliteDesk-800-G2-SFF:~/COBOL$ 

答案 1 :(得分:0)

更完整的例子:

INPUT-OUTPUT SECTION.
  FILE-CONTROL.
    SELECT IN_FILE ASSIGN TO IN_FILE
     ORGANIZATION     IS SEQUENTIAL
     ACCESS MODE      IS SEQUENTIAL
     FILE STATUS      IS FSTAT.
FILE SECTION.
  FD IN_FILE
  VALUE OF ID IS IN_FILE_NAME.
    01 IN_POST.
      03 FIELDA      PIC X(14).
      03 FIELDB      PIC X(10).
      03 FIELDC      PIC X(32).
      03 FIELDD      PIC X(03).
      03 FIELDE      PIC X(02).

WORKING-STORAGE SECTION.
  01 IN_FILE_NAME PIC X(22).
  01 FSTAT PIC XX.


PROCEDURE DIVISION. 
    MOVE "FILE1.DAT" to IN_FILE_NAME
    OPEN INPUT IN_FILE
    CLOSE IN_FILE

    MOVE "FILE2.DAT" to IN_FILE_NAME
    OPEN INPUT IN_FILE
    CLOSE IN_FILE

    MOVE "FILE3.DAT" to IN_FILE_NAME
    OPEN INPUT IN_FILE
    CLOSE IN_FILE
STOP RUN.