-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile.c++
32 lines (26 loc) · 1.06 KB
/
file.c++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include "shared.h++"
#include "file.h++"
// A function that will read a file at a path into an allocated char pointer buffer
char* pathtobuf(std::filesystem::path path) {
return pathtobufsize(path,NULL);
}
// A function that will read a file at a path into an allocated char pointer buffer
char* pathtobufsize(std::filesystem::path path, int *size) {
FILE *fptr;
long length;
char *buf;
fptr = fopen(path.string().c_str(), "rb"); // Open file for reading
if (!fptr) // Return NULL on failure
return NULL;
fseek(fptr, 0, SEEK_END); // Seek to the end of the file
length = ftell(fptr); // Find out how many bytes into the file we are
buf = (char*)malloc(length+1); // Allocate a buffer for the entire length of the file and a null terminator
fseek(fptr, 0, SEEK_SET); // Go back to the beginning of the file
fread(buf, length, 1, fptr); // Read the contents of the file in to the buffer
fclose(fptr); // Close the file
buf[length] = 0; // Null terminator
if (size != NULL) {
*size = length;
}
return buf; // Return the buffer
}