Casus: a file is being read, looking like so:
*
key
new line
new line
*
key
new line
new line
*
So relevant text blocks start and finish with * The amount of lines per block varies. The data item searching for the appropriate keys of the data to be displayed is “seek”
My question is: could the coding be improved?
Patrick
10 do while string(1:1).NE.‘*’)
read(1,“(a)”,iostat=stat)string
end do
read(1,“(a)”,iostat=stat)string
if (index(string,seek(1:3)).NE.1) goto 10
do while string(1:1).NE.'') . . . . . the astrisk between the quotes is not being shown by the site
read(1,“(a)”,iostat=stat)string
print_, string !the program uses a subroutine to print
end do
This code was generated using ChatGPT. Does it meet your expectations?
program ReadFile
implicit none
character(len=5) :: keyword = "key1"
character(len=100) :: line
logical :: found_keyword = .false.
integer :: nunit
integer :: status
! Open the file for reading
open(newunit=nunit, file='testfile.txt', status='old', action='read')
! Read the file until the end or until keyword is found
do
read(nunit, '(A)', iostat=status) line
if (status < 0) exit ! End of file reached
if (trim(line) == keyword) then
found_keyword = .true.
exit
endif
end do
! Print the text block for keyword
if (found_keyword) then
do
read(nunit, '(A)', iostat=status) line
if (status < 0 .or. line(1:1) == '*') exit ! End of file or next key reached
write(*, '(A)') line
end do
else
write(*, '(A)') 'keyword not found.'
endif
! Close the file
close(nunit)
end program ReadFile
testfile.txt:
*
key1
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Sed ac elit vitae purus aliquam luctus.
Aliquam vitae fringilla risus.
Proin interdum dignissim diam at mattis.
Sed sed metus tristique, tincidunt sapien a, consectetur felis.
Mauris eu dolor a mauris tincidunt elementum.
Vivamus ac aliquam massa.
Donec venenatis aliquet velit, eu scelerisque justo luctus ac.
Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae;
Nam ullamcorper est non mi cursus, sed vestibulum ante pellentesque.
*
key2
Proin interdum dignissim diam at mattis.
Sed sed metus tristique, tincidunt sapien a, consectetur felis.
Donec venenatis aliquet velit, eu scelerisque justo luctus ac.
Vivamus ac aliquam massa.
*
key3
Sed sed metus tristique, tincidunt sapien a, consectetur felis.
*
key4
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae;
Nam ullamcorper est non mi cursus, sed vestibulum ante pellentesque.
*
The code was generated entirely using GPT, and I didn’t expect it to compile correctly without any errors. Therefore, I hastily posted it here without making any changes (except for adding ‘nunit’). I thought GPT could provide a quick idea.