COBOL中的文件处理

时间:2014-10-19 11:30:10

标签: cobol

我想编写一个cobol程序来读取包含4个字段(EMPID,NAME,STREAM,GRADE)的EMP-GRADE文件,并显示在输出中得分为“A”的员工的详细信息。我使用在线Cobol编译器。

IDENTIFICATION DIVISION.
PROGRAM-ID. SAMPLE1.
ENVIRONMENT DIVISION. 
INPUT-OUTPUT SECTION. 
FILE-CONTROL.
SELECT EMPFILE ASSIGN TO 'input.txt'
ORGANIZATION IS SEQUENTIAL 
ACCESS MODE IS SEQUENTIAL
FILE STATUS IS WS-FILE-STATUS.
SELECT EMPA ASSIGN TO 'util.cobc'
ORGANIZATION IS SEQUENTIAL 
ACCESS MODE IS SEQUENTIAL. 
DATA DIVISION. 
FILE SECTION. 
FD EMPFILE. 
01 NEWFILE. 
05 FS-EMPID PIC 9(6). 
05 FILLER PIC X(50).
05 FS-NAME PIC A(10).
05 FILLER PIC X(50).
05 FS-STREAM PIC A(10).
05 FILLER PIC X(50).
05 FS-GRADE PIC A(1).
05 FILLER PIC X(50).
FD EMPA.
01 OUTFILE.
05 FS-EMPID-OUT PIC 9(6). 
05 FILLER PIC X(50).
05 FS-NAME-OUT PIC A(10).
05 FILLER PIC X(50).
05 FS-STREAM-OUT PIC A(10).
05 FILLER PIC X(50).
05 FS-GRADE-OUT PIC A(1).
05 FILLER PIC X(50).
WORKING-STORAGE SECTION. 
01 WS-EOF PIC A(1) VALUE "N". 
01 WS-FILE-STATUS PIC X(2). 
PROCEDURE DIVISION. 
MAIN-PARA. 
OPEN INPUT EMPFILE 
OPEN OUTPUT EMPA
PERFORM READ-PARA THRU READ-PARA-EXIT
Perform Until WS-EOF = "Y"
    IF FS-GRADE='A'
        MOVE NEWFILE TO OUTFILE
        WRITE OUTFILE
        END-WRITE
        DISPLAY OUTFILE
    ELSE
    DISPLAY 'NO A GRADE STUDENT IN THE LIST'
    END-IF
    PERFORM READ-PARA THRU READ-PARA-EXIT 
    END-PERFORM
CLOSE EMPFILE.
CLOSE EMPA.
STOP RUN. 
MAIN-PARA-EXIT. 
EXIT. 
READ-PARA. 
READ EMPFILE
AT END MOVE "Y" TO WS-EOF 
NOT AT END DISPLAY NEWFILE 
END-READ. 
READ-PARA-EXIT.
EXIT.

以上是我的更新代码,然后我在'input.txt'中输入了输入,输出如下

11111   AISHU   JAVA    B
22222   RANJU   MAINF   A

列表中没有一个等级的学生

2 个答案:

答案 0 :(得分:2)

试试这段代码:

PROCEDURE DIVISION. 
MAIN-PARA. 
    OPEN INPUT EMPFILE 
    OPEN OUTPUT EMPA
    PERFORM READ-PARA THRU READ-PARA-EXIT UNTIL WS-EOF = ‘Y’
    CLOSE EMPFILE.
    CLOSE EMPA.
    STOP RUN. 
MAIN-PARA-EXIT. 
    EXIT. 
READ-PARA. 
    READ EMPFILE
        AT END 
            MOVE "Y" TO WS-EOF 
            IF WS-F='M' THEN
                DISPLAY 'NO A GRADE STUDENT IN THE LIST'
            END-IF
        NOT AT END DISPLAY NEWFILE
            IF FS-GRADE='A' THEN
                MOVE ‘M’ TO WS-F
                MOVE NEWFILE TO OUTFILE
                WRITE OUTFILE
                END-WRITE
                DISPLAY OUTFILE
            ELSE
                CONTINUE 
            END-IF
    END-READ. 
READ-PARA-EXIT.
    EXIT.

答案 1 :(得分:1)

您正在使用

读取整个输入文件
PERFORM READ-PARA THRU READ-PARA-EXIT UNTIL WS-EOF="Y"

语句。您必须改为阅读记录,处理记录,阅读下一条记录,处理记录等等。

OPEN INPUT EMPFILE  
OPEN OUTPUT EMPA 
PERFORM READ-PARA THRU READ-PARA-EXIT

Perform Until WS-EOF = "Y"
    IF FS-GRADE='A'
        MOVE NEWFILE TO OUTFILE
        WRITE OUTFILE
        DISPLAY OUTFILE
    END-IF
    PERFORM READ-PARA THRU READ-PARA-EXIT 
End-Perform

CLOSE EMPFILE 
CLOSE EMPA 
STOP RUN.

根据练习的实际要求,可能会有许多其他改进,但我认为这可以解决您的直接问题。

请注意PERFORMs的两个READ-PARA。第一种有时被称为启动读取,这是一种有用的学习技巧。