command_argument_count()返回程序名之后的命令行参数个数,get_command_argument按编号读取参数文本,并可同时返回所需长度和状态。它们常用于让同一可执行文件接收输入文件、网格规模和运行选项;适合批处理和脚本调用,读取后仍需验证参数个数、长度、状态及文本内容。
语法结构
count = command_argument_count()
call get_command_argument(number [, value, length, status])
- 普通参数从1开始编号,number=0请求程序调用名;command_argument_count不包含程序名。
- value是默认character标量;空间不足时内容被截断,length仍报告完整参数所需长度,status可报告截断或读取失败。
- 命令行参数都是文本。数值参数需要另行解析,含空格的单个参数需要由shell加引号传入。
本文代码
! 读取输入文件名和步数两个命令行参数。
program cliArgsDemo
implicit none
character(len=128) :: inputFile, stepText
integer :: argumentCount, argumentLength, argumentStatus
argumentCount = command_argument_count()
if (argumentCount /= 2) then
print "(A)", "用法:./cliArgsDemo 输入文件 步数"
stop 1
end if
call get_command_argument(1, inputFile, length=argumentLength, &
status=argumentStatus)
if (argumentStatus /= 0) error stop "无法读取输入文件参数"
print "(A,I0)", "参数个数:", argumentCount
print "(A,A)", "输入文件:", trim(inputFile)
print "(A,I0)", "文件名长度:", argumentLength
call get_command_argument(2, stepText, length=argumentLength, &
status=argumentStatus)
if (argumentStatus /= 0) error stop "无法读取步数参数"
print "(A,A)", "步数文本:", trim(stepText)
print "(A,I0)", "步数参数长度:", argumentLength
end program cliArgsDemo
编译运行
(base) hong@hongdeMacBook-Pro 070.cliArgs % gfortran -Wall -Wextra -std=f2018 exampleCLIArgs.f90 -o cliArgsDemo
(base) hong@hongdeMacBook-Pro 070.cliArgs % ./cliArgsDemo temperature.csv 3600
参数个数:2
输入文件:temperature.csv
文件名长度:15
步数文本:3600
步数参数长度:4
现象分析
运行命令在程序名后传入temperature.csv和3600,因此command_argument_count返回2。程序先验证数量,避免读取不存在的参数。
第1个参数共有15个字符,第2个参数共有4个字符;get_command_argument分别把完整长度写入argumentLength,并把内容写入定长接收变量。
3600目前仍是字符文本,而不是integer。后续若参与循环或计算,应使用内部文件read解析并检查iostat,不能把字符外观当作数值类型。
核心知识点
- 参数计数不包含程序名,参数编号从1开始。
- get_command_argument可同时返回值、完整长度和状态。
- 接收变量过短会截断,稳健代码应检查length和status。
- 所有命令行参数最初都是字符数据。