温馨提示×

Ubuntu中Fortran代码如何进行输入输出操作

小樊
50
2025-09-23 01:53:12
栏目: 智能运维

在Ubuntu中,使用Fortran进行输入输出操作通常涉及读取和写入文件,以及从命令行接收参数。以下是一些基本的示例:

1. 从命令行读取参数

你可以使用getarg函数从命令行读取参数。

program read_args
    implicit none
    integer :: i, num_args
    character(len=100) :: arg

    num_args = command_argument_count()
    print *, 'Number of arguments:', num_args

    do i = 1, num_args
        call getarg(i, arg)
        print *, 'Argument', i, ':', trim(arg)
    end do
end program read_args

编译并运行这个程序:

gfortran -o read_args read_args.f90
./read_args hello world 123

2. 写入文件

你可以使用open, write, 和 close语句来写入文件。

program write_to_file
    implicit none
    integer :: iounit, i
    character(len=100) :: filename

    filename = 'output.txt'
    open(unit=iounit, file=filename, status='replace', action='write')

    do i = 1, 10
        write(iounit, *) 'Line', i
    end do

    close(iounit)
    print *, 'Data written to', filename
end program write_to_file

编译并运行这个程序:

gfortran -o write_to_file write_to_file.f90
./write_to_file

3. 读取文件

你可以使用open, read, 和 close语句来读取文件。

program read_from_file
    implicit none
    integer :: iounit, i
    character(len=100) :: filename
    character(len=100) :: line

    filename = 'output.txt'
    open(unit=iounit, file=filename, status='old', action='read')

    i = 1
    do while (.true.)
        read(iounit, '(A)', iostat=i) line
        if (i /= 0) exit
        print *, 'Line', i, ':', trim(line)
    end do

    close(iounit)
    print *, 'Finished reading', filename
end program read_from_file

编译并运行这个程序:

gfortran -o read_from_file read_from_file.f90
./read_from_file

4. 标准输入输出

你也可以使用Fortran的标准输入输出函数,如print, read, 和 write

program std_io
    implicit none
    integer :: num
    character(len=100) :: name

    print *, 'Enter your name:'
    read(*, *) name
    print *, 'Hello,', trim(name), '!'

    print *, 'Enter a number:'
    read(*, *) num
    print *, 'You entered:', num
end program std_io

编译并运行这个程序:

gfortran -o std_io std_io.f90
./std_io

这些示例涵盖了Fortran在Ubuntu中进行基本输入输出操作的常见方法。你可以根据需要扩展和修改这些示例。

0