Sign in Join
Wiki copytemporary

Basic Pascal Tutorial/Chapter 2/Files/zh CN: what changed

Revision 2 to 3. Removed lines have a minus sign; added lines have a plus sign.

OldNewLine
112D - 文件操作 (原作者: Tao Yue, 状态: 未更改)
22
33读取文件,但不是从控制台(键盘)中读取数据,可以这样:
44
55``` pascal
66read (文件变量, 参数列表);
77write (文件变量, 参数列表);
88```
99
1010同样用 `readln` 和 `writeln`。文件变量声明如下:
1111
1212``` pascal
1313var
1414 ...
1515 filein, fileout : text;
1616```
1717
1818`text` 数据类型指定该文件仅是纯文本形式。
1919
2020操作文件时,需要先声明变量,以读取或者写入数据;我们需要将磁盘上的文件与变量相关联,可以使用以下2种方式之一,通常:
2121
22-```
22+```text
2323reset (文件变量, '文件名');
2424rewrite (文件变量, '文件名');
2525```
2626
2727`reset` 将对打开的文件进行读取或重写。 使用`reset`操作文件,只能进行`read`、`readln`操作。 使用`rewrite`操作文件,只能进行`write`、`rewrite`操作。
2828
2929Turbo Pascal 使用引入赋值。首先将文件名赋值给一变量,之后调用`reset`或`rewrite`。
3030
3131``` pascal
3232assign (文件变量, '文件名');
3333reset (文件变量);
3434```
3535
3636操作系统不同,路径表达方法也不一。Windows使用反斜杠(如 `c:\directory\name.pas`),而MacOS、Linux使用斜杠。
3737
3838操作完成后,你需要关闭它:
3939
4040``` pascal
4141close (文件标识符);
4242```
4343
4444下面是一个操作文件的示例,程序运行在DOS下,将读取file1.txt内容,写入到file2.txt中。
4545
4646``` pascal
4747program CopyOneByteFile;
4848
4949var
5050 mychar : char;
5151 filein, fileout : text;
5252
5353begin
5454 assign (filein, 'c:\file1.txt');
5555 reset (filein);
5656 assign (fileout, 'c:\file2.txt');
5757 rewrite (fileout);
5858 read (filein, mychar);
5959 write (fileout, mychar);
6060 close(filein);
6161 close(fileout)
6262end.
6363```
6464
6565| | | |
6666|----|----|----|
6767| [[Basic Pascal Tutorial/Chapter 2/Formatting output/zh CN|上一页]] | [[Basic Pascal Tutorial/Contents/zh CN|目录]] | [[Basic Pascal Tutorial/Chapter 2/EOLN and EOF/zh CN|下一页]] |
6868
6969---
7070*From the Free Pascal wiki, page "Basic Pascal Tutorial/Chapter 2/Files/zh CN", as it stood on 2022-08-20 after a change by Kai Burghardt, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).*

Back to history