如果你想使用 Unix 命令$ wc -l
,你可以调用 Fortran 子程序execute_command_line
,它是许多 Fortran 编译器常用的,gfortran
包括在内。
这是一个工作示例,它计算nlines
调用文件的行数 ,style.gnuplot
然后通过覆盖最后nlines
一行来附加一些行。style.gnuplot
PROGRAM numLines
IMPLICIT NONE
integer, parameter :: n = 100
integer :: i, nLines
real, parameter :: x0 = -3.14, xEnd = 3.14
real :: dx
real, dimension (:), allocatable :: x, fun
allocate(x(0:n)) ! Allocate the x array
allocate(fun(0:n)) ! Allocate the fun array
dx = abs(xEnd-x0)/n
x(0:n) = [(x0+i*dx, i = 0,n)] ! Create the x array
fun(0:n) = [(sin(x0+i*dx), i = 0,n)] ! Create the fun array
open(unit=1,file="plotFunction.dat")
DO i=0,size(x)-1
write(1,*) x(i), ' ', fun(i) ! Save the function to a file to plot
END DO
close(unit=1)
deallocate(x) ! Deallocate the x array
deallocate(fun) ! Deallocate the fun array
open(unit=7, file="style.gnuplot")
write(7,*) "set title 'y = sin(x)' font 'times, 24'"
write(7,*) "set tics font 'times, 20'"
write(7,*) "set key font 'times,20'"
write(7,*) "set grid"
write(7,*) "set key spacing 1.5"
write(7,*) "plot '<cat' u 1:2 w l lw 2 linecolor rgb 'orange' notitle "
close(unit=7)
CALL execute_command_line("wc -l style.gnuplot | cut -f1 -d' ' > nlines.file") ! COunt the lines
open(unit=1,file='nlines.file')
read(1,*) nlines ! Here the number of lines is saved to a variable
close(unit=1)
CALL execute_command_line("rm nlines.file") ! Remove nlines.file
CALL execute_command_line("cat plotFunction.dat | gnuplot -p style.gnuplot") ! Show the plot within the executable
open(unit=7,file="style.gnuplot")
DO i = 1,nLines-1
read(7,*) ! Read the file untile the penultimate row,
END DO ! then append the other rows
write(7,*) "set object rectangle at -3.14,0 size char 1, char 1", &
" fillcolor rgb 'blue' fillstyle solid border lt 2 lw 1.5"
write(7,*) "set object rectangle at 0,0 size char 1, char 1", &
" fillcolor rgb 'blue' fillstyle solid border lt 2 lw 1.5"
write(7,*) "set object rectangle at 3.14,0 size char 1, char 1", &
" fillcolor rgb 'blue' fillstyle solid border lt 2 lw 1.5"
write(7,*) "plot 'plotFunction.dat' u 1:2 w l lw 2 linecolor rgb 'orange' notitle"
close(unit=7)
CALL execute_command_line("gnuplot -p 'style.gnuplot'") ! Load again style.gnulot with the appended lines
END PROGRAM numLines
我的代码可能不优雅,但它似乎工作!