在Linux下使用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
stop
end if
! Perform file operations here
close(unit_number)
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
stop
end if
do
read(unit_number, '(A)', iostat=iostat) line
if (iostat /= 0) exit
print *, line
end do
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 = 10
open(unit=unit_number, file=filename, status='replace', action='write', iostat=iostat)
if (iostat /= 0) then
print *, 'Error opening file:', iostat
stop
end if
write(unit_number, *) 'Hello, World!'
write(unit_number, *) 'This is a Fortran file operation example.'
close(unit_number)
end program write_file_example
program append_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='write', position='append', iostat=iostat)
if (iostat /= 0) then
print *, 'Error opening file:', iostat
stop
end if
write(unit_number, *) 'This line will be appended to the file.'
close(unit_number)
end program append_file_example
这些示例展示了如何在Fortran中使用内置的I/O语句和函数进行基本的文件操作。你可以根据自己的需求修改这些示例,以实现更复杂的文件操作。