Assign

From Free Pascal wiki
(Redirected from AssignFile)
Jump to navigationJump to search

The Borland Pascal procedure assign associates a file variable with an external entity (e. g. a device file or a file on disk). Assign only operates on the program’s internal management data and has otherwise no immediate observable effect.

usage

In non-ISO modes the FPC needs files to be explicitly associated with external entities. This can be achieved with assign. The first parameter is a file variable, the second parameter specifies a path.

program assignDemo(input, output, stdErr);
var
	FD: text;
begin
	assign(FD, '/tmp/assignDemo.txt');
	assign(FD, '/root/.bashrc');
end.

Note, you can run this program without any troubles as any user on any platform. Nonexistent path components (e. g. directories), missing privileges to eventually access the file or any path component, or unacceptable characters (usually chr(0)) do not pose a problem to assign. It merely operates on internal management data.

application

  • Assign is used before operating on any file variable.
    program assignApplication(input, output, stdErr);
    var
    	executable: file of Byte;
    begin
    	assign(executable, paramStr(0));
    	fileMode := 0; { 0 = read-only; only relevant for `file of …` variables }
    	reset(executable);
    	writeLn(paramStr(0), ' has a size of ', fileSize(executable), ' Bytes.');
    end.
    
  • Assign can be used to redirect standard files input/output. Our Hello, World program needs only a few changes as highlighted:
    program redirectDemo(input, output, stdErr);
    const
    	blackhole = {$ifDef Linux}   '/dev/null' + {$endIf}
    	            {$ifDef Windows} 'nul'       + {$endIf}
    	            '';
    begin
    	assign(output, blackhole);
    	rewrite(output);
    	writeLn('Hello world!');
    end.
    

caveats

  • Regardless of the utilized string data type, assign can only process paths of up to 255 Bytes. This limitation comes from the internally used fileRec/textRec. Relative paths in conjunction with working directories cannot overcome this. Cf. FPC issue 35185.
  • Since assign only operates on internal management data, specifying illegal paths is accepted. It is even possible to supply an empty string as a path. The specific behavior on a file variable bearing an empty file name depends on the used I/O routine.

notes

  • If {$modeSwitch objPas+} (automatically set via {$mode objFPC} or {$mode Delphi}), the procedure assignFile is available, too. It performs the very same task.
  • In Extended Pascal a combination of bindingType and bind are usually used to achieve linking a file variable with an external entity.