Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- typedef struct file_t {
- char *name;
- FILE *file;
- char *(*read)(File*);
- long int (*size)(File*);
- } File;
- long int file_t__size(File *this) {
- fseek(this->file, 0, SEEK_END);
- long int fsize = ftell();
- rewind(this->file);
- return fsize;
- }
- char *file_t__read(File *this) {
- long int fsize = this->size(this);
- char *buff = malloc(fsize + 1);
- buff[fsize] = '\0';
- long int rsize = fread(buff, 1, fsize, this->file);
- if(rsize != fsize) {
- free(buff);
- return NULL;
- }
- return buff;
- }
- file_t open_file(char *fname) {
- return (File) {
- fname,
- fopen(fname, "r"),
- &file_t__read,
- &file_t__size
- };
- }
- int main() {
- char *fname = malloc(1024);
- printf("Enter file name (max. 1024 chars): ");
- scanf("%s1024", fname);
- File file = open_file(fname);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement