Fortran Coder

查看: 1204|回复: 4
打印 上一主题 下一主题

[文件读写] 如何保证写入文件时不覆盖已有的字符串

[复制链接]

5

帖子

3

主题

0

精华

入门

F 币
33 元
贡献
13 点
跳转到指定楼层
楼主
发表于 2023-10-23 20:47:39 | 显示全部楼层 回帖奖励 |倒序浏览 |阅读模式
各位老师好,有一个程序,内部有一个功能是将输出的几个参数写到上一个文件夹中名为array-bmax.txt的文件(107)中,由于这个程序需要并行执行,多个并行计算的结果都需要写入array-bmax.txt文件中,实际执行时发现写入文件时,只能写入最后一个计算出的结果,其他的结果都被覆盖掉了,请问这段代码应该如何修改,才能实现将并行输出的结果都写入文件array-bmax.txt中?
[Fortran] 纯文本查看 复制代码
program main
    use commondata
    
    implicit none
    integer i,style,traj,files,n,j,du
    real*8 xseed
    real bmax,Et,RMAX,RBAR,S
    character*100 ftmp
    character(100) :: cmd
    character(10) :: opinion
    character(80) :: inp_name
    
    
    call ReadInputFile(inp_name,style,traj,files,n,j,Et,bmax,RMAX,RBAR,S)

    open(107,file='../array-bmax.txt',status='old',position='append')

    5 fsbatch='sbatch.sc'
    open(105,file=fsbatch)
    
    ftmp='cp /home/O3/'
    fcpinp='script.cp' 
    open(101,file=fcpinp)
    write(101,'(a)')trim(ftmp)//'new/venus-E.e ./'
    
    call init_random_seed()
    
    do i=1,files !nfile
      call random_number(xseed)
      call writeinp(i,xseed,style,traj,files,n,j,Et,bmax,inp_name,RMAX,RBAR,S)
    enddo
    
    write(101,'(a)') 'cp ./sbatch.sc ./'//trim(inp_name)//'-inpark'
    write(101,'(a)') 'cd '//trim(inp_name)//'-inpark'
    write(101,'(a)') 'chmod +x sbatch.sc'
    write(101,'(a)') "sed -i 's/^.\{19\}/scancel /g' scancel.x" 
    write(101,'(a)') 'chmod +x scancel.x'
    
    close(101)
    
    call execute_command_line("chmod +x script.cp")
    call execute_command_line("./script.cp")
    call execute_command_line('sleep 1s')
    call execute_command_line("rm -r inp0* run0*")
    
    if (style == 1) then
       open(106,file=trim(inp_name)//'-inpark/test-bmax')
       write(106,'(a,f3.1)') "(*.*)zzz---wait---",bmax
       call execute_command_line('sleep 90s')
    
       call testbmax(inp_name,traj,du)
       if (du == 0) then
            call execute_command_line("rm -r sbatch.sc script.cp")
            bmax=bmax+0.1d0
            goto 5
        elseif (du == 1) then
            write(107,'(f5.1,I3,I4,f5.1)') Et,n,j,bmax
            close(107)
        endif
    elseif (style == 0) then
        stop
    endif
    end program main

分享到:  微信微信
收藏收藏 点赞点赞 点踩点踩

5

帖子

3

主题

0

精华

入门

F 币
33 元
贡献
13 点
沙发
 楼主| 发表于 2023-10-24 19:38:05 | 显示全部楼层
谢谢楼上各位老师的建议和帮助,这个程序昨天测试时,我把open107文件的命令改到写入命令前,就可以实现输出都写到107文件里了:
[Fortran] 纯文本查看 复制代码
elseif (du == 1) then
  open(107,file='../array-bmax.txt',position='append')
  write(107,'(f5.1,I3,I4,f5.1)') Et,n,j,bmax
  close(107)
endif
这样这个程序暂且可以运行了,就是其中逻辑我还没想明白,我再好好想想。
您需要登录后才可以回帖 登录 | 极速注册

本版积分规则

捐赠本站|Archiver|关于我们 About Us|小黑屋|Fcode ( 京ICP备18005632-2号 )

GMT+8, 2024-5-18 11:08

Powered by Tencent X3.4

© 2013-2024 Tencent

快速回复 返回顶部 返回列表