Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
541 views
in Technique[技术] by (71.8m points)

fortran90 - How to write at specific lines in fortran

I want to copy a file from a folder and write at specific lines of the file using fortran. I am using Windows, GNU fortran compiler. Here is sample file and code. file1.txt

1 *
2 **
3 ***
4 ****
5 *****
6 ******
7 *******
8 ********
9 *********
10 **********

Here is code: I defined some variables. Only if two criteria match (particular variable value and line number), I want to write in the new text in the file. I tried using system command to copy, but it fails. Can anyone tell me correct way of using this? And program got run time error FORMAT present for unformatted text

program read

   integer :: a,b,c,d,e
   CHARACTER (LEN=200) :: str

   a=0
   b=1
   c=0
   d=1
   e=0

    !call system ("copy" // "D:est1file1.txt"," ", // "D:")
    !This command fails

   open (unit=10, file="file1.txt", access="direct", & 
form="unformatted",  action="readwrite", recl=100 )

   do i=1,10,1
    read (10,*) str 

    if(a==0 .AND. i==3) then
        write(10,100) 'This is ',i,' line'
    else if(b==0 .AND. i==4) then
        write(10,100) 'This is ',i,' line'
    else if(c==0 .AND. i==5) then
        write(10,100) 'This is ',i,' line'
    else if(d==0 .AND. i==6) then
        write(10,100) 'This is ',i,' line'
    else if(e==0 .AND. i==7) then
        write(10,100) 'This is ',i,' line'
    100 format (2a,i0,1X)
    end if
   end do

   close (unit=10)  
end program 

Can I read and write in the same file? Please share your comments. I referred to some questions Fortran - How to write data to specific line in the file? but couldn't help me.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are a couple things wrong with your system call. First, you need a space between copy and the first argument. Second, you need a destination file, not just a folder. Also, you should only be using string concatenaters //, not commas. For example, if you want to copy to a new file name file2.txt, you can use a system call like this:

call system ("copy " // "D:est1file1.txt " // "D:est1file2.txt")

Because you're using literal strings instead of variables, you can simplify it by getting rid of the concatenaters:

call system ("copy D:est1file1.txt D:est1file2.txt")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...