Sign in Join
Wiki copytemporary

Basic Pascal Tutorial/Chapter 2/Files: what changed

Revision 2 to 3. 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-```
22+```text
2323reset(File_variable, 'filename.extension');
2424rewrite(File_variable, 'filename.extension');
2525```
2626
2727`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`.
2828
2929Turbo Pascal introduced the assign notation. First you assign a filename to a variable, then you call `reset` or `rewrite` using only the variable.
3030
3131``` pascal
3232assign(File_variable, 'filename.extension');
3333reset(File_variable);
3434```
3535
3636The 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.
3737
3838After you're done with the file, you can close it with:
3939
4040``` pascal
4141close (File_variable);
4242```
4343
4444Here'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:
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*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