Files and Buffers

Jerry Ferris biomechanical at iomailu.io
Thu Feb 1 21:36:52 UTC 2018


Hello,

I'm developing a program that will either receive data from stdin 
or a file, and pass it along to a function for processing. I want 
to place this data into a buffer so there only has to be one 
version of the function. However, since I'm new to D, I'm unsure 
how to go about this in the most idiomatic way.

Thus my questions are:
* Is there a simpler way to copy a file's contents into a buffer?
* Is the above superfluous due to some mechanism?
* Basically, am I doing this in a convoluted and inefficient 
manner?

Here is the current code:

---
/**
  * Copy file contents to buffer
  */
auto file = File(filename, "rb");
auto compBuf = new OutBuffer();

{
	import std.conv : to;

	immutable fileSize = filename.getSize.to!uint;
	compBuf.reserve(fileSize);
	
	foreach (ubyte[] buf; file.byChunk(fileSize))
	{
		compBuf.write(buf);
	}
}

// Decompress takes an OutBuffer w/ compressed data and returns 
an OutBuffer w/ the uncompressed version
auto decompBuf = compBuf.decompress;
---

Thank you in advance, and I apologize if this is a very stupid 
question.

Regards,
Jerry Ferris


More information about the Digitalmars-d-learn mailing list