@@ -98,7 +98,23 @@ module stdlib_system
98
98
! ! Windows, and various UNIX-like environments. On unsupported operating systems, the function will return `.false.`.
99
99
! !
100
100
public :: is_directory
101
-
101
+
102
+ ! ! version: experimental
103
+ ! !
104
+ ! ! Deletes a specified file from the filesystem.
105
+ ! ! ([Specification](../page/specs/stdlib_system.html#delete_file-delete-a-file))
106
+ ! !
107
+ ! !### Summary
108
+ ! ! Subroutine to safely delete a file from the filesystem. It handles errors gracefully using the library's `state_type`.
109
+ ! !
110
+ ! !### Description
111
+ ! !
112
+ ! ! This subroutine deletes a specified file. If the file does not exist, or if it is a directory or inaccessible,
113
+ ! ! an error is raised. Errors are handled using the library's `state_type` mechanism. If the optional `err` argument
114
+ ! ! is not provided, exceptions trigger an `error stop`.
115
+ ! !
116
+ public :: delete_file
117
+
102
118
! ! version: experimental
103
119
! !
104
120
! ! Returns the file path of the null device, which discards all data written to it.
@@ -707,4 +723,47 @@ end function process_null_device
707
723
708
724
end function null_device
709
725
726
+ ! > Delete a file at the given path.
727
+ subroutine delete_file (path , err )
728
+ character (* ), intent (in ) :: path
729
+ type (state_type), optional , intent (out ) :: err
730
+
731
+ ! > Local variables
732
+ integer :: file_unit, ios
733
+ type (state_type) :: err0
734
+ character (len= 512 ) :: msg
735
+ logical :: file_exists
736
+
737
+ ! Check if the path exists
738
+ inquire (file= path, exist= file_exists)
739
+ if (.not. file_exists) then
740
+ ! File does not exist, return error status
741
+ err0 = state_type(STDLIB_FS_ERROR,' Cannot delete' ,path,' : file does not exist' )
742
+ call err0% handle(err)
743
+ return
744
+ endif
745
+
746
+ ! Verify the file is not a directory
747
+ if (is_directory(path)) then
748
+ ! If unable to open, assume it's a directory or inaccessible
749
+ err0 = state_type(STDLIB_FS_ERROR,' Cannot delete' ,path,' - is a directory' )
750
+ call err0% handle(err)
751
+ return
752
+ end if
753
+
754
+ ! Close and delete the file
755
+ open (newunit= file_unit, file= path, status= ' old' , iostat= ios, iomsg= msg)
756
+ if (ios /= 0 ) then
757
+ err0 = state_type(STDLIB_FS_ERROR,' Cannot delete' ,path,' -' ,msg)
758
+ call err0% handle(err)
759
+ return
760
+ end if
761
+ close (unit= file_unit, status= ' delete' , iostat= ios, iomsg= msg)
762
+ if (ios /= 0 ) then
763
+ err0 = state_type(STDLIB_FS_ERROR,' Cannot delete' ,path,' -' ,msg)
764
+ call err0% handle(err)
765
+ return
766
+ end if
767
+ end subroutine delete_file
768
+
710
769
end module stdlib_system
0 commit comments