Skip to content

Instantly share code, notes, and snippets.

@ErnyTech
Last active December 16, 2018 11:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ErnyTech/c9de9f47fb3af11e5ea7cca3bf7c931d to your computer and use it in GitHub Desktop.
Save ErnyTech/c9de9f47fb3af11e5ea7cca3bf7c931d to your computer and use it in GitHub Desktop.
import std.stdio;
import std.conv;
import core.stdc.stdio;
import core.stdc.stdlib;
import std.string;
struct fileData {
void* data;
size_t numData;
}
@trusted fileData readFile(string filename) {
FILE* file;
static int BUFFER_SIZE = 10;
void* data = null;
size_t currentSize = 0;
size_t currentData;
size_t offset = 0;
file = fopen(filename.toStringz, "r");
if(file == null) {
throw new StringException("Failed to open file: " ~ filename);
}
do {
data = realloc(data, currentSize + BUFFER_SIZE);
if (data == null) {
throw new StringException("Memory allocation failed for: " ~ to!string(currentSize + BUFFER_SIZE));
}
currentSize += BUFFER_SIZE;
currentData = fread(&data[offset], 1, BUFFER_SIZE, file);
offset += currentData;
} while (currentData == BUFFER_SIZE);
fclose(file);
fileData fd = {data, offset};
return fd;
}
@trusted char[] getStringFile(fileData file) {
char* dataChar = cast(char*) file.data;
return dataChar[0..file.numData];
}
@safe void main() {
fileData file = readFile("/proc/version");
writeln(getStringFile(file));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment