tcdaniel
tcdaniel

Reputation: 203

Parse Fortran String Like A File

I want to pass a string from C to Fortran and then process it line-by-line as if I was reading a file. Is this possible?

Example String - contains newlines

File description: this file contains stuff
3 Values
  1     Description
  2     Another description
  3     More text

Then, I would like to parse the string line-by-line, like a file. Similar to this:

subroutine READ_STR(str, len)
character str(len),desc*70

read(str,'(a)') desc
read(str,*) n
do 10 i=1,n
read(str,*) parm(i)
10    continue

Upvotes: 1

Views: 274

Answers (1)

IanH
IanH

Reputation: 21441

Not without significant "manual" intervention. There are a couple of issues:

  • The newline character has no special meaning in an internal file. Records in an internal file correspond to elements in an array. You would either need to first manually preprocess your character scalar into an array, or use a single READ that skipped over the newline characters.

  • If you did process the string into an array, then internal files do not maintain a file position between parent READ statements. You would need to manually track the current record yourself, or process the entire array with a single READ statement that accessed multiple records.

If you have variable width fields, then writing a format specification to process everything in a single READ could be problematic, though this depends on the details of the input.

Upvotes: 2

Related Questions