Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- program read_input
- ! Maximilian Kubillus, 2013
- ! Reads a file, removes all comments and trims the trailing whitespace
- ! into a new file. If you want a variable or simple output instead:
- ! Change 'write(write_id,*) trim(buffer)' in line 54 accordingly.
- implicit none
- ! Variable for the file identifier number
- integer :: read_id, write_id
- ! IO-status for open() and read()
- integer :: read_ios, read_status, write_ios
- ! Index variables for loops
- integer :: ii, jj
- ! Line buffer for the file
- character(len=1024) :: buffer
- ! Line with dynamic length (so trailing spaces are cut)
- character :: line
- ! Comment symbol
- character :: comment
- ! Filenames to read and write
- character(len=:), allocatable :: in_file, out_file
- ! Format variable for buffer
- character(len=*), parameter :: lineformat = '(A1024)'
- ! Set up some variables. You might want to change these!
- comment = '#'
- in_file = 'dummy.in'
- out_file = 'dummy.parsed'
- ! This numbers are completely arbitrary... ;-)
- read_id = 42
- write_id = 43
- open(read_id, file=in_file, form='formatted', iostat=read_ios, action='read')
- open(write_id, file=out_file, iostat=write_ios, action='write')
- if(read_ios == 0) then
- do
- read(read_id, fmt=lineformat, iostat=read_status) buffer
- ! If we are at the end of the line, we exit the loop.
- if(read_status /= 0) exit
- ! Here we check if the line contains a comment.
- ii = index(buffer, comment)
- if(ii == 0) then
- ! If there is no comment in the line, we align the line to the left.
- buffer = adjustl(buffer)
- else
- ! We cut out the comment part of the line if one exists and
- ! then align to the left again.
- buffer = adjustl(buffer(1:ii-1))
- endif
- ! Now, if the length of a buffer (w/o trailing whitespace) is 0, we
- ! won't print it.
- if(len(trim(buffer)) /= 0) then
- ! Check if opening the output file was successful
- if(write_ios == 0) then
- write (write_id,*) trim(buffer)
- ! If you want to print the output
- ! into the terminal, uncomment this:
- ! write (*,*) trim(buffer)
- else
- STOP 'IOError: Problem opening output file!'
- endif
- endif
- enddo
- else if(read_ios < 0) then
- ! If we are at the end of the file, we stop the program
- STOP
- else
- ! If the ios is something > 0 we exit with an error message.
- STOP 'IOError: Could not open input file!'
- endif
- close(read_id)
- end program read_input
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement