在Ubuntu上进行Fortran文件操作,你可以使用Fortran标准库中提供的I/O子例程。以下是一些基本的文件操作示例:
program open_file_example
implicit none
integer :: unit_number, iostat
character(len=*) :: filename
filename = 'example.txt'
unit_number = 10
open(unit=unit_number, file=filename, status='old', action='read', iostat=iostat)
if (iostat /= 0) then
print *, 'Error opening file:', iostat
else
print *, 'File opened successfully.'
end if
end program open_file_example
program read_file_example
implicit none
integer :: unit_number, iostat, num_read
character(len=100) :: line
unit_number = 10
open(unit=unit_number, file='example.txt', status='old', action='read', iostat=iostat)
if (iostat /= 0) then
print *, 'Error opening file:', iostat
else
do
read(unit_number, '(A)', iostat=iostat) line
if (iostat /= 0) exit
print *, line
end do
end if
close(unit_number)
end program read_file_example
program write_file_example
implicit none
integer :: unit_number, iostat
character(len=*) :: filename
filename = 'example.txt'
unit_number = 20
open(unit=unit_number, file=filename, status='replace', action='write', iostat=iostat)
if (iostat /= 0) then
print *, 'Error opening file:', iostat
else
write(unit_number, *) 'Hello, World!'
print *, 'Data written to file successfully.'
end if
close(unit_number)
end program write_file_example
program close_file_example
implicit none
integer :: unit_number, iostat
unit_number = 10
close(unit=unit_number, iostat=iostat)
if (iostat /= 0) then
print *, 'Error closing file:', iostat
else
print *, 'File closed successfully.'
end if
end program close_file_example
在这些示例中,我们使用了open
、read
、write
和close
等I/O子例程来进行文件操作。注意,你需要确保在使用文件之前检查iostat
变量,以确保操作成功。此外,你还可以使用其他I/O子例程和格式化选项来满足你的需求。