Skip to content

Conversation

@ibeuler
Copy link

@ibeuler ibeuler commented Aug 7, 2025

Error Explanation and Motivation

Problem:
At line 20 of Eatools_so.f90 (unit = 61), the program throws a runtime error:

Fortran runtime error: File already opened in another unit

This happens because the code attempts to open the file Cij.dat on unit 61, but that file is already open on the same or a different Fortran unit without being closed first. Fortran forbids opening the same file multiple times simultaneously without closing it, causing the program to crash.

Additionally, the original code had several issues:

  • No check if the file was already open before attempting to open it.
  • Incorrect use of inquire(unit=61, opened=isOpen) where isOpen was undeclared or incorrectly typed.
  • Invalid syntax like close(file="Cij.dat") — Fortran close expects a unit number, not a filename.
  • Missing error handling when file opening failed.

What this fix improves:

  • Safe File Handling:
    Uses inquire(file="Cij.dat", opened=isOpen) to check if the file is already open (independent of unit). If open, it safely closes the file on the known unit (61) before reopening, avoiding multiple opens.

  • Error Checking:
    Adds iostat=ios to the open statement to detect failures. If opening fails, the program prints a clear error message and exits gracefully.

  • Correct Syntax and Declarations:
    Fixes incorrect close syntax to use unit numbers instead of filenames.
    Declares variables isOpen (logical) and ios (integer) properly.

  • Improved Robustness:
    Prevents runtime crashes caused by file access conflicts.
    Helps users quickly identify missing or inaccessible input files.
    Makes the code more portable and maintainable.


Summary:
This pull request fixes file handling in Eatools_so.f90 to avoid the “file already opened” runtime error by adding proper file open checks, correct closing, error handling, and variable declarations. The changes improve program stability, prevent crashes, and provide clearer diagnostics for file-related issues.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant