# Writing to a file or a string with the same function

**URL:** <https://fortran-lang.discourse.group/t/writing-to-a-file-or-a-string-with-the-same-function/8448>\
**Category:** Uncategorized\
**Created:** [August 8, 2024, 11:24am UTC](https://fortran-lang.discourse.group/t/writing-to-a-file-or-a-string-with-the-same-function/8448 "2024-08-08T11:24:13Z")\
**Posts on this page:** 1\
**Showing post:** 1

<div class="post-metadata">

**Author:** ![nja](https://avatars.discourse-cdn.com/v4/letter/n/ed8c4c/32.png) [@nja](https://fortran-lang.discourse.group/u/nja)\
**Post date:** [August 8, 2024, 11:24am UTC](https://fortran-lang.discourse.group/t/writing-to-a-file-or-a-string-with-the-same-function/8448/1 "2024-08-08T11:24:13Z")

</div>

I have various functions that carefully log values in a file, along the line of :

```fortran
subroutine log_conditions(unit, temperature, pressure)

  integer, intent(in) :: unit
  real, intent(in) :: temperature, pressure
  
  character(len=10) :: date, time
  
  call date_and_time(date, time)
  
  write(unit, "(a, a, a, a, f0.3, a, f6.0, a)") "[", date, time, "] The temperature is ", &
  temperature, "°C, the pressure is", pressure, " Pa."

end subroutine

```

I can pass a unit number associated with a file, or with the standard output/error.

But can I make this function work on a string ? The `write` statement in itself can take an integer _or_ a string :

```fortran
  character(len=40) :: string
  integer :: unit
  
  unit = 6
  write(unit, "(a)") "Logging to a unit"
  write(string, "(a)") "Logging to a string"
  
  print *, "string = '", trim(string), "'"

```

But this does not work on my `log_conditions` function, because it accepts only an integer as first argument. Somehow I would have to bind a unit to `string`, just like `open` binds a unit to a file.

Is this possible?

I could, of course, make two versions of my function, one taking an integer, the other a string, but it would be a shame.

---

_[View the full topic](https://fortran-lang.discourse.group/t/writing-to-a-file-or-a-string-with-the-same-function/8448)._
