SUBROUTINE read_txt_real(filename, vector, num_values)
IMPLICIT NONE
INTEGER :: ios
INTEGER :: i
character(len=100), intent(in) :: filename
real(kind=8), intent(out), DIMENSION(:), ALLOCATABLE :: vector
integer, intent(out) :: num_values ! 用于存储文件中的数据个数也就是矩阵维度
! 尝试打开文件
OPEN (UNIT=10, FILE=filename, STATUS='OLD', ACTION='READ', IOSTAT=ios)
IF (ios /= 0) THEN
PRINT *, "Error opening file"
ELSE
PRINT *, "File opened successfully"
! 计算文件中的数据个数
num_values = 0
DO
READ (10, *, IOSTAT=ios)
IF (ios /= 0) EXIT
num_values = num_values + 1
END DO
! 回到文件开头
REWIND (10)
ALLOCATE (vector(num_values)) ! 分配数组空间
! 读取文件中的所有实数值并存储到数组 t_true 中
DO i = 1, num_values
READ (10, *) vector(i)
PRINT *, "Read value: ", vector(i)
END DO
END IF
CLOSE (10)
END SUBROUTINE read_txt_real
SUBROUTINE read_txt_ingter(filename, vector, num_values)
IMPLICIT NONE
INTEGER :: ios
INTEGER :: i
character(len=100), intent(in) :: filename
INTEGER, intent(out), DIMENSION(:), ALLOCATABLE :: vector
integer, intent(out) :: num_values ! 用于存储文件中的数据个数也就是矩阵维度
! 尝试打开文件
OPEN (UNIT=10, FILE=filename, STATUS='OLD', ACTION='READ', IOSTAT=ios)
IF (ios /= 0) THEN
PRINT *, "Error opening file"
ELSE
PRINT *, "File opened successfully"
! 计算文件中的数据个数
num_values = 0
DO
READ (10, *, IOSTAT=ios)
IF (ios /= 0) EXIT
num_values = num_values + 1
END DO
! 回到文件开头
REWIND (10)
ALLOCATE (vector(num_values)) ! 分配数组空间
! 读取文件中的所有实数值并存储到数组 t_true 中
DO i = 1, num_values
READ (10, *) vector(i)
PRINT *, "Read value: ", vector(i)
END DO
END IF
CLOSE (10)
END SUBROUTINE read_txt_ingter
SUBROUTINE output_txt_real(filename, A, A_row, A_col)
implicit none
!// =========================输入要读取的矩阵名称=======================
integer, intent(in) :: A_row, A_col
real(kind=8), intent(in), DIMENSION(:, :), ALLOCATABLE :: A ! 假设读写A矩阵
character(len=100), intent(in) :: filename
!// =========================定义其他信息=======================
integer :: status
integer :: i, j
! 打开文件并将矩阵数据写入
open (unit=10, file=filename, status='replace', action='write', iostat=status)
! 写入矩阵数据,按照列主序将矩阵排成一列
do j = 1, A_col
do i = 1, A_row
write (10, *) (A(i, j)) !(10, *) 用*可以将原始的数据导入,按照原始数据精度
end do
end do
close (10)
print *, 'Matrix data has been written to ', trim(filename)
end SUBROUTINE output_txt_real
本文对fortran从txt中写入文件和读取文件进行了代码整理,共三个SUBROUTINE
SUBROUTINE read_txt_real(filename, vector, num_values)与SUBROUTINE read_txt_ingter(filename, vector, num_values)为从txt中读取文件,filename为txt所在路径+文件名
SUBROUTINE output_txt_real(filename, A, A_row, A_col)为将一个矩阵按列主序写入txt文件(列主序便于储存,生成的txt为一列数值);该子程序没有特意定义输出value的精度,按原矩阵中储存格式输出