Fortran Coder

标题: fortran怎样判断文件夹是否存在? [打印本页]

作者: xuanyz    时间: 2020-4-9 22:20
标题: fortran怎样判断文件夹是否存在?
本帖最后由 kyra 于 2020-4-10 08:07 编辑

打算在当前目录下的2003336的文件夹下打开一个名称为data.txt的文件并输入单个整型数据500
编程思路如下,判断在当前目录下是否存在2003336文件夹,如果存在2003336文件夹屏幕输出 'the file exist'
                       如果不存则屏幕输出'the file no exist and will be created'并创建该文件夹
                       接下来改变当前目录到2003336文件夹
                       最后打开文件data.txt写入整型数据500
                       程序结束
程序结果勉强可以接收,但存在一些问题:
(1)不论程序运行几次,标识文件夹2003336是否存在的数据istat始终===0,很显然不对呀?????
(2)第一次运行程序屏幕输出 'the file no exist and will be created',标识2003336文件夹不存在需要创建,但第二次第三次依然屏幕输出  'the file no exist and will be created' 并且屏幕还有一行
"子目录或文件已经存在"的语句提示。代表2003336文件夹应经存在了,也就是说不需要再次创建2003336文件夹了。这与自己的设定输出'the file no exist and will be created' 又有矛盾了???
(3)又仔细查了一下inquire函数,了解到inquire函数似乎只能查询文件,而不能查询文件夹,请问在fortran中有没有可以查询文件夹是否存在的函数或者判断方法?或者是其他可以实现目的的方法,谢谢了

图片分别表示第一次运行结果和第二次及更多次运行结果的情形

               代码如下:
[Fortran] 纯文本查看 复制代码
program main
character elname1*4, elname2*8, folder_name*15,filename*20
integer istat,istat2
real a
write(elname1, '(i4)') 200
write(elname2, '(i8)') 3336
folder_name=trim(adjustl(elname1))//trim(adjustl(elname2))   
inquire(file=trim(folder_name), exist=istat)                                 
write(*,*)istat
if (istat) then
   print*, 'the file exist'
else
   print*, 'the file no exist and will be created'
   istat2=system( "Md "//trim(folder_name))
end if
istat2=CHDIR(trim(folder_name)) !改变当前目录到到文件夹
filename='data.txt' !打开写入数据的txt文件
open(308,file=filename,status='replace',form='formatted')
write(308,*) 500
close(308)
end program main


第一次运行结果.JPG (31.67 KB, 下载次数: 258)

第一次运行结果

第一次运行结果

第二次及多次运行结果.JPG (38.69 KB, 下载次数: 248)

第二次几多次运行结果

第二次几多次运行结果

作者: kyra    时间: 2020-4-10 08:11
你用intel fortran的话,可以用
Inquire(DIRECTORY="2003336",exist=b)
作者: li913    时间: 2020-4-10 08:40
fortran标准没有判断文件夹的功能,你可以直接open该文件夹中一个文件 open(10,file='2003336\data.txt',iostat=i,iomsg=msg) ,配合iostat 和 iomsg就知道是否存在文件夹。
[Fortran] 纯文本查看 复制代码
program test
  integer i, k
  character(80) msg
  open(10,file='2003336\data.txt',iostat=i,iomsg=msg)
  if(i/=0) then
    call execute_command_line('md 2003336')
    open(10,file='2003336\data.txt',iostat=i,iomsg=msg)
  end if
  if(i/=0) then
    write(*,"(a)") trim(msg)
  end if
  pause
end

作者: xuanyz    时间: 2020-4-10 09:33
感谢kyra和li913,我才用了kyra的方案,再次感谢




欢迎光临 Fortran Coder (http://bbs.fcode.cn/) Powered by Discuz! X3.2