How to keep a file open?

Hi there,

I'm reading data from a serial port and in case of an event I'd like to write the data to a file.
For this I have a small little function that opens the file to append one line of JSON data to it.
And then it closes the file when it leaves the scope of the function.
Since there may be "a lot" of data, it feels like opening and closing the file all the time comes with unnecessary overhead.
In order to replace the "write_to_file" function with a "write_to_some_database" in the future, I would like to keep the handling modular. How would you do that?

Best,
Frank

Open the file once as part of your application setup (likely right at the beginning of main), and pass it to the function every time you need to write to it.

Sure, it would work, but it doesn't feel right :slight_smile:
What would I do if I defined the file inside a UI and did not know it from the beginning?

You could declare a struct EventReport (or some better name for your context). The struct has the file as a member, so wherever you want to start reporting you creteate one by calling a named constructor EventReport::open(), and then you make the small funktion that appends a json line a method of that struct.

Anything that wants to append an event will need to borrow the struct, but that would still be true for the database handle or connection pool if you used a database instead. And it's modular, the borrowed EventReport and the append call would be the same if you changed the implementation of EventReport.

1 Like

Then you would wrap it in an Option.

1 Like

I'll give that a try, let's see ... :slight_smile:

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.