program inout implicit none * Program to show input / output. This also shows * use of getarg character*80 infile, outfile, line integer*4 in_unit, out_unit ! Unit numbers integer*4 num_arg ! Number of arguments in command line integer*4 ierr ! IOSTAT error integer*4 count(2) ! Counter for number of lines and comments logical eof ! End-of-file logical set true when EOF **** See if output file passed via command line. * ** Note this code may not work on all systems because iargc may not * be available. ** num_arg = iargc() if( num_arg.ge.1 ) then call getarg(1,outfile) out_unit = 11 open(out_unit,file=outfile,status='new',iostat=ierr) * Test to see if error opening file. If there is then * send the output to the screen (unit 6) if( ierr.ne.0 ) then write(*,120) ierr, outfile 120 format('IOSTAT ierr ',i5,' opening new file ',a,/, . 'Outputing to screen') out_unit = 6 endif else * No file name passed, so send output to screen out_unit = 6 ! Screen output endif **** Read the source files infile = 'inout.f' in_unit = 10 open(in_unit,file=infile,status='old',iostat=ierr) * See if there is an error opening file if( ierr.ne.0 ) then * Error open unit, report and stop write(*,140) ierr, infile 140 format('IOSTAT ierr ',i5,' opening old file ',a,/, . 'Program ending!') ! Comment at end of program stop 'Input file not found' endif ***** File opened OK; initialize line counters and loop count(1) = 0 count(2) = 0 eof = .false. do while ( .not.eof ) * Read line from file read(in_unit,'(a)',iostat=ierr ) line * Process line if there is no error if( ierr.eq.0 ) then * Increment total number of lines count(1) = count(1) + 1 if( line(1:1).eq.'*' .or. line(1:1).eq.'c' ) then * Comment line, so output and increment count count(2) = count(2) + 1 * Only out part of line past column 7 write(out_unit,'(a,"Z")') line(7:) endif else * Error reading file. Mark as EOF eof = .true. endif enddo * Output the line counts write(*,220) count 220 format('There were ',i4,' lines and ',i4,' comments') * Close the file units close(in_unit) * Only close the output if it is not unit 6. if( out_unit.ne.6 ) close(out_unit) end