Opens a file (Specification)
To open a file to read:
u = open("somefile.txt") ! The default `mode` is "rt"
u = open("somefile.txt", "r")
To open a file to write:
u = open("somefile.txt", "w")
To append to the end of the file if it exists:
u = open("somefile.txt", "a")
Type | Intent | Optional | Attributes | Name | ||
---|---|---|---|---|---|---|
character(len=*), | intent(in) | :: | filename | |||
character(len=*), | intent(in), | optional | :: | mode | ||
integer, | intent(out), | optional | :: | iostat |
integer function open(filename, mode, iostat) result(u) !! version: experimental !! !! Opens a file !! ([Specification](../page/specs/stdlib_io.html#description_1)) !! !!##### Behavior !! !! !! To open a file to read: !! !!```fortran !! u = open("somefile.txt") ! The default `mode` is "rt" !! u = open("somefile.txt", "r") !!``` !! !! To open a file to write: !! !!```fortran !! u = open("somefile.txt", "w") !!``` !! !! To append to the end of the file if it exists: !! !!```fortran !! u = open("somefile.txt", "a") !!``` character(*), intent(in) :: filename character(*), intent(in), optional :: mode integer, intent(out), optional :: iostat character(3) :: mode_ character(:),allocatable :: action_, position_, status_, access_, form_ mode_ = parse_mode(optval(mode, "")) select case (mode_(1:2)) case('r') action_='read' position_='asis' status_='old' case('w') action_='write' position_='asis' status_='replace' case('a') action_='write' position_='append' status_='old' case('x') action_='write' position_='asis' status_='new' case('r+') action_='readwrite' position_='asis' status_='old' case('w+') action_='readwrite' position_='asis' status_='replace' case('a+') action_='readwrite' position_='append' status_='old' case('x+') action_='readwrite' position_='asis' status_='new' case default call error_stop("Unsupported mode: "//mode_(1:2)) end select select case (mode_(3:3)) case('t') form_='formatted' case('b') form_='unformatted' case default call error_stop("Unsupported mode: "//mode_(3:3)) end select access_ = 'stream' if (present(iostat)) then open(newunit=u, file=filename, & action = action_, position = position_, status = status_, & access = access_, form = form_, & iostat = iostat) else open(newunit=u, file=filename, & action = action_, position = position_, status = status_, & access = access_, form = form_) end if end function open