读取文件的方式:
顺序读取的方式(A是定义读取文件的名称,可随意命名,文件地址一般为绝对路径)
ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT A ASSIGN TO 'C:OCinput.txt' ORGANIZATION IS LINE SEQUENTIAL.
具体全部代码:(顺序读取一个文件)
1 IDENTIFICATION DIVISION. 2 PROGRAM-ID. HELLO. 3 4 ENVIRONMENT DIVISION. 5 INPUT-OUTPUT SECTION. 6 FILE-CONTROL. 7 SELECT A ASSIGN TO 'C:OCinput.txt' 8 ORGANIZATION IS LINE SEQUENTIAL. 9 10 DATA DIVISION. 11 FILE SECTION. 12 *FD语句主要用来描述与文件记录相关的物理信息,如记录实际格式,长度等。 13 FD A. 14 01 STUDENT-FILE. 15 05 STUDENT-ID PIC 9(5). 16 05 WS-NAME PIC A(25). 17 18 19 WORKING-STORAGE SECTION. 20 01 WS-STUDENT. 21 05 WS-STUDENT-ID PIC 9(5). 22 05 WS-NAME PIC A(25). 23 01 WS-EOF PIC A(1). 24 25 *程序运行主体部分 26 PROCEDURE DIVISION. 27 *打开文件A作为输入文件,类似于c中的读取文件 28 OPEN INPUT A. 29 *循环读取文件A,并将数据放入WS-STUDENT,并打印WS-STUDENT 30 PERFORM UNTIL WS-EOF='Y' 31 READ A INTO WS-STUDENT 32 AT END MOVE 'Y' TO WS-EOF 33 NOT AT END DISPLAY WS-STUDENT 34 *读取完毕后,关闭所有读取,结束循环,关闭文件A 35 END-READ 36 END-PERFORM. 37 CLOSE A. 38 STOP RUN.
写入文件:
IDENTIFICATION DIVISION. PROGRAM-ID. HELLO. ENVIRONMENT DIVISION. INPUT-OUTPUT SECTION. FILE-CONTROL. *写入文件,一般为绝对文件 SELECT STUDENT ASSIGN TO 'C:OCinput.txt' ORGANIZATION IS SEQUENTIAL ACCESS IS SEQUENTIAL. DATA DIVISION. FILE SECTION. *FD语句主要用来描述与文件记录相关的物理信息,如记录实际格式,长度等。 FD STUDENT. 01 STUDENT-FILE. 05 STUDENT-ID PIC 9(5). 05 NAME PIC A(25). 05 CLAS PIC X(3). WORKING-STORAGE SECTION. 01 WS-STUDENT. 05 WS-STUDENT-ID PIC 9(5). 05 WS-NAME PIC A(25). 05 WS-CLASS PIC X(3). *程序运行主体部分 PROCEDURE DIVISION. *打开要写入文件 OPEN EXTEND STUDENT. MOVE 1000 TO STUDENT-ID. MOVE 'TIM' TO NAME. MOVE '10' TO CLAS. *将暂存文件STUDENT-FILE写入文件 WRITE STUDENT-FILE END-WRITE. CLOSE STUDENT. STOP RUN.