C – Get rid of file-based communication

Get rid of file-based communication… here is a solution to the problem.

Get rid of file-based communication

I have to use two C programs that communicate through file-based interfaces. That is, each of them has a main loop that polls three or four files (fopen, fscanf), uses react on what it reads, and finally makes its own changes to the file (fprintf) for other processes to read.

Now I have to condense these two programs into one program, with minimal changes to the program logic and general code. However, mainly for aesthetic reasons, I should replace file-based communication with something in memory.

I

can imagine some hacky approach to accomplish this, but I’m sure stackoverflow will give me a hint for a nifty solution 🙂

Solution

Since you tagged this Linux, I will suggest open_memstream. It was added to POSIX in POSIX 2008, but it has been available on glibc-based Linux systems for a long time. Basically, it lets you open a FILE*, which is actually a dynamically growing buffer in memory so you don’t have to change too much code. This “file” is write-only, but you can simply read it on the buffer using sscanf instead of fscanf, or use fmemopen (it has no dynamic growth semantics, but is very convenient for reading from memory buffers.)

Related Problems and Solutions