Last active
September 11, 2022 19:46
-
-
Save opsJson/58e951e9276f2347d567ad798b8c25bb to your computer and use it in GitHub Desktop.
Write variables to file and read file to variable, easily.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
void *ftob(const char *file, unsigned int *size, ...) { | |
FILE *fp; | |
unsigned char *buffer; | |
long int _size; | |
if ((fp = fopen(file, "rb")) == NULL) { | |
fprintf(stderr, "ERROR: Could not open '%s'\n", file); | |
return NULL; | |
} | |
if (fseek(fp, 0, SEEK_END) != 0) { | |
fprintf(stderr, "ERROR: Could not set cursor to end of '%s'.\n", file); | |
return NULL; | |
} | |
if ((_size = ftell(fp)) == -1) { | |
fprintf(stderr, "ERROR: Could not get cursor position of '%s'.\n", file); | |
return NULL; | |
} | |
if (fseek(fp, 0, SEEK_SET) != 0) { | |
fprintf(stderr, "ERROR: Could not set cursor to end of '%s'.\n", file); | |
return NULL; | |
} | |
if ((buffer = malloc(sizeof(char) * _size + sizeof(char))) == NULL) { | |
fprintf(stderr, "ERROR: Could not allocate %li bytes to hold file content.\n", _size); | |
fclose(fp); | |
return NULL; | |
} | |
if (fread(buffer, 1, _size, fp) != (unsigned)_size) { | |
fprintf(stderr, "ERROR: Could not read %li bytes from file.\n", _size); | |
fclose(fp); | |
return NULL; | |
} | |
buffer[_size] = 0; | |
fclose(fp); | |
if (size) *size = _size; | |
return buffer; | |
} | |
#define ftob(...) ftob(__VA_ARGS__, 0) | |
int btof(const char *file, void *data, unsigned int size) { | |
FILE *fp; | |
unsigned int amount; | |
if ((fp = fopen(file, "wb")) == NULL) return -1; | |
amount = fwrite(data, size, 1, fp); | |
fclose(fp); | |
return amount; | |
} | |
/*/////////////////////////////////// | |
Testing: | |
///////////////////////////////////*/ | |
int main(void) { | |
unsigned int size = -1; | |
char *file = ftob("file.txt", &size); | |
printf("Size: %i\n", size); | |
printf("Content: [%s]\n", file); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment