I have a data file that I want to print to stdout. Is this possible to do in fortran without having to read the data into arrays and then printing the arrays?
Thanks
I have a data file that I want to print to stdout. Is this possible to do in fortran without having to read the data into arrays and then printing the arrays?
Thanks
You can open the file for stream access and process it one character at a time in a loop, until end of file is reached. I have no idea how (in)efficient this may be for large data files, but it saves you from having to define a character variable with a length large enough to hold the longest line, which requires an educated guess.
program echostd use, intrinsic :: iso_fortran_env, only: iostat_end implicit none character(*), parameter :: file_name = 'data.txt' integer :: lun, io_status character :: char open(newunit=lun, file=file_name, access='stream', status='old', & action='read') print *, '--- Content of file: ' // file_name // ' ---' do read(lun, iostat=io_status) char if(io_status == iostat_end) exit if(io_status > 0) error stop '*** Error occurred while reading file. ***' write(*, '(a)', advance='no') char end do print *, '--- End of content of file: ' // file_name // ' ---' close(lun) end program echostd
I've used two fortran 2008 features, but they can both easily be done without, if your compiler doesn't support them yet.
One is the newunit= specifier; if your compiler doesn't support this, you can of course use a predefined unit number.
The other is the error stop statement; simply remove the error part if needed.
OK, I'm just mildly curious where you're using Fortran.
You can just read it into a character variable inside a loop. Fortran has a statement like
read (7,*,end=10) name where you can continue reading until you reach and EOF (and it will jump to line 10 on EOF).