Sign in Join
Wiki copytemporary

Basic Pascal Tutorial/Chapter 2/Files: what changed

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

OldNewLine
112D - Files (author: Tao Yue, state: changed)
22
33Reading from a file instead of the console (keyboard) can be done by:
44
55``` pascal
66read(File_variable, Argument_list);
77write(File_variable, Argument_list);
88```
99
1010Similarly with `readln` and `writeln`. The output is stored into the variables named in `Argument_list`. `File_variable` is declared as follows:
1111
1212``` pascal
1313var
1414 ...
1515 Filein, Fileout : text;
1616```
1717
1818The `text` data type indicates that the file is just plain text.
1919
2020After declaring a variable for the file, and before reading from or writing to it, we need to associate the variable with the filename on the disk and open the file. This can be done in one of two ways. Typically:
2121
22-`reset(File_variable, 'filename.extension');`\
23-`rewrite(File_variable, 'filename.extension');`
22+```
23+reset(File_variable, 'filename.extension');
24+rewrite(File_variable, 'filename.extension');
25+```
2426
2527`reset` opens a file for reading, and rewrite opens a file for writing. A file opened with `reset` can only be used with `read` and `readln`. A file opened with `rewrite` can only be used with `write` and `writeln`.
2628
2729Turbo Pascal introduced the assign notation. First you assign a filename to a variable, then you call `reset` or `rewrite` using only the variable.
2830
2931``` pascal
3032assign(File_variable, 'filename.extension');
3133reset(File_variable);
3234```
3335
3436The method of representing the path differs depending on your operating system. Windows uses backslashes and drive letters due to its DOS heritage (e.g. `c:\directory\name.pas`), while FreeBSD, macOS and Linux use forward slashes due to their UNIX heritage.
3537
3638After you're done with the file, you can close it with:
3739
3840``` pascal
3941close (File_variable);
4042```
4143
4244Here's an example of a program that uses files. This program was written for Turbo Pascal and DOS, and will create file2.txt with the first character from file1.txt:
4345
4446``` pascal
4547program CopyOneByteFile;
4648
4749var
4850 Mychar : char;
4951 Filein, Fileout : text;
5052
5153begin
5254 assign(Filein, 'c:\file1.txt');
5355 reset(Filein);
5456 assign(Fileout, 'c:\file2.txt');
5557 rewrite(Fileout);
5658 read(Filein, Mychar);
5759 write(Fileout, Mychar);
5860 close(Filein);
5961 close(Fileout)
6062end.
6163```
6264
6365---
6466*From the Free Pascal wiki, page "Basic Pascal Tutorial/Chapter 2/Files", 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