Opening a file on unit 5 or 6

夙愿已清 提交于 2019-11-29 12:11:31

Fortran has no magic unit numbers. The Fortran standard says nothing about 5, 6 or any other valid unit number being used for a special purpose. As such you are free to use the open statement to associate any valid unit number with a file. However traditionally for reasons that pre-date me 5 and 6 have been pre-associated with the keyboard and screen, as you say. Now still you can change the association by use of the open statement and that is fine save for the confusion it can cause, so most people I know recommend avoiding this and using unit numbers of 10 and upwards. Also because 5 and 6 are not guaranteed to be associated with the default input and output devices I would recommend against their use, preferring * or, in more modern code, the named constants input_unit, output_unit and error_unit from the iso_fortran_env intrinsic module.

So in summary you've got the right idea, and I'm not surprised you're confused.

Vladimir F

Nothing in the standard says units 5 and 6 have any special meaning although in practice standard input and standard output are often pre-connected to 5 and 6.

Module iso_fortran_env from Fortran 2008 contains constants

INPUT_UNIT
OUTPUT_UNIT
ERROR_UNIT

with the unit numbers where standard input, standard output and standard error are connected. These are allowed to be different than 5 and 6.

Opening a file in unit that is in use causes the unit to be associated with the new file.

For example the Cray Fortran manual says:

Unit numbers 100, 101, and 102 are permanently associated with the standard input, standard output, and standard error files, respectively.

That means if you open some other file as unit 5 or 6 standard input and standard output still have some other unit where they are pre-connected and they will not be closed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!