Basic Pascal Tutorial/Chapter 2/Files/zh CN: what changed
Revision 0 to 1. Removed lines have a minus sign; added lines have a plus sign.
Title: Basic Pascal Tutorial/Chapter 2/Files/zh CN
| Old | New | Line | |
|---|---|---|---|
| 1 | + | 2D - 文件操作 (原作者: Tao Yue, 状态: 未更改) | |
| 2 | + | ||
| 3 | + | 读取文件,但不是从控制台(键盘)中读取数据,可以这样: | |
| 4 | + | ||
| 5 | + | ``` pascal | |
| 6 | + | read (文件变量, 参数列表); | |
| 7 | + | write (文件变量, 参数列表); | |
| 8 | + | ``` | |
| 9 | + | ||
| 10 | + | 同样用 `readln` 和 `writeln`。文件变量声明如下: | |
| 11 | + | ||
| 12 | + | ``` pascal | |
| 13 | + | var | |
| 14 | + | ... | |
| 15 | + | filein, fileout : text; | |
| 16 | + | ``` | |
| 17 | + | ||
| 18 | + | `text` 数据类型指定该文件仅是纯文本形式。 | |
| 19 | + | ||
| 20 | + | 操作文件时,需要先声明变量,以读取或者写入数据;我们需要将磁盘上的文件与变量相关联,可以使用以下2种方式之一,通常: | |
| 21 | + | ||
| 22 | + | `reset (文件变量, '文件名');`\ | |
| 23 | + | `rewrite (文件变量, '文件名');` | |
| 24 | + | ||
| 25 | + | `reset` 将对打开的文件进行读取或重写。 使用`reset`操作文件,只能进行`read`、`readln`操作。 使用`rewrite`操作文件,只能进行`write`、`rewrite`操作。 | |
| 26 | + | ||
| 27 | + | Turbo Pascal 使用引入赋值。首先将文件名赋值给一变量,之后调用`reset`或`rewrite`。 | |
| 28 | + | ||
| 29 | + | ``` pascal | |
| 30 | + | assign (文件变量, '文件名'); | |
| 31 | + | reset (文件变量); | |
| 32 | + | ``` | |
| 33 | + | ||
| 34 | + | 操作系统不同,路径表达方法也不一。Windows使用反斜杠(如 `c:\directory\name.pas`),而MacOS、Linux使用斜杠。 | |
| 35 | + | ||
| 36 | + | 操作完成后,你需要关闭它: | |
| 37 | + | ||
| 38 | + | ``` pascal | |
| 39 | + | close (文件标识符); | |
| 40 | + | ``` | |
| 41 | + | ||
| 42 | + | 下面是一个操作文件的示例,程序运行在DOS下,将读取file1.txt内容,写入到file2.txt中。 | |
| 43 | + | ||
| 44 | + | ``` pascal | |
| 45 | + | program CopyOneByteFile; | |
| 46 | + | ||
| 47 | + | var | |
| 48 | + | mychar : char; | |
| 49 | + | filein, fileout : text; | |
| 50 | + | ||
| 51 | + | begin | |
| 52 | + | assign (filein, 'c:\file1.txt'); | |
| 53 | + | reset (filein); | |
| 54 | + | assign (fileout, 'c:\file2.txt'); | |
| 55 | + | rewrite (fileout); | |
| 56 | + | read (filein, mychar); | |
| 57 | + | write (fileout, mychar); | |
| 58 | + | close(filein); | |
| 59 | + | close(fileout) | |
| 60 | + | end. | |
| 61 | + | ``` | |
| 62 | + | ||
| 63 | + | | | | | | |
| 64 | + | |----|----|----| | |
| 65 | + | | [[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|下一页]] | | |
| 66 | + | ||
| 67 | + | --- | |
| 68 | + | *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).* |
