1 module stdlow.io.file;
2 import core.stdc.stdio;
3 import core.stdc.stdlib;
4 import std.string;
5 import std.conv;
6 
7 const BUFFER_SIZE = 8192;
8 struct fileData {
9 	void* data;
10 	size_t num_data;
11 }
12 
13 @trusted fileData readFile(string filename) {
14 	auto file = fopen(filename.toStringz, "r");
15 	void* ptr_data;
16 	auto current_size = 0;
17 	auto offset = 0;
18 	if(file == null) {
19 		throw new StringException("Failed to open file: " ~ filename);
20 	}
21 	scope(exit) fclose(file);
22 
23 	while(true) {
24 		ptr_data = realloc(ptr_data, current_size + BUFFER_SIZE);
25 		if (ptr_data == null) {
26 			throw new StringException("Memory allocation failed for: " ~ to!string(current_size + BUFFER_SIZE));
27 		}
28 		current_size += BUFFER_SIZE;
29 		auto current_data = fread(&ptr_data[offset], 1, BUFFER_SIZE, file);
30 		offset += current_data;
31 		if (current_data != BUFFER_SIZE) {
32 			size_t delta = BUFFER_SIZE - current_data;
33 			ptr_data = realloc(ptr_data, current_size - delta);
34 			if (ptr_data == null) {
35 				throw new StringException("Memory allocation failed for: " ~ to!string(current_size + BUFFER_SIZE));
36 			}
37 			break;
38 		}
39 	}
40 	
41 	if(ferror(file)) {
42 		throw new StringException("File read error!");
43 	}
44 	if (!feof(file)) {
45 			throw new StringException("File read error!");
46 	}
47 	fileData fd = {ptr_data, offset};
48 	return fd;
49 }
50 
51 @trusted void writeFile(fileData filedata, string filename) {
52 	auto file = fopen(filename.toStringz, "w");
53     auto ptr_data = filedata.data;
54     auto current_size = 0;
55 	if(file == null) {
56 		throw new StringException("Failed to open file: " ~ filename);
57 	}
58 	scope(exit) fclose(file);
59 	
60 	do {
61 		auto delta = filedata.num_data - current_size;
62 		size_t buffer;
63 		if (delta < BUFFER_SIZE) {
64 			buffer = delta;
65 		} else {
66 			buffer = BUFFER_SIZE;
67 		}
68 		auto result = fwrite(ptr_data, 1, buffer, file);
69 		if (result < buffer) {
70 			throw new StringException("File write error");
71 		}
72 		current_size += buffer;
73 		ptr_data += buffer;
74 	} while (current_size != filedata.num_data);
75 }