1

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

3
  • You can read it into a character variable line by line, therefore avoiding the arrays (why?), and just print it out, but you have to read it into something. What are yoou trying to accomplish, if it's no secret? Commented Apr 19, 2011 at 14:56
  • But wouldnt I have to set the length of the character string that way? Commented Apr 19, 2011 at 14:58
  • Yes, but just put it something crazy long which you know none of your lines is longer than. For example, 500? Commented Apr 19, 2011 at 15:15

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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).

2 Comments

How does that work? Is 'name' just a character variable? The problem is that I would need to set the length of the character variable to at least the length of the file
Yes, name is a character variable. The length of name should be the maximum length of the line, not the file. If your file had 10 strings, and the longest line you expected was 20 characters, then you could make name 20 characters long (not 200).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.